• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 475
  • Last Modified:

C# Replace Function Error

string strFileName = "";
// retrieve the name of the file that is posted.
strFileName = oFile.PostedFile.FileName;
strFileName = Path.GetFileName(strFileName);

I am getting the following error at this statement --------- strFileName.Replace(":","_")
error: 'strFileName.Replace' does not exist

I am trying to achieve the following. If the strFileName consists of a COLON(:) charater, i wish to replace it by UNDERSCORE(_). Since i cannot save any file with a COLON in its name.

Also please suggest a function which checks for all invalid characters in a new file save operation.

1 Solution
try this

strFileName = strFileName.Replace(":", "_");
Assuming you're on 2.0 (not 1.1), the following should strip out all invalid characters (replacing with an underscore):

            foreach (char c in System.IO.Path.GetInvalidFileNameChars())
                strFileName = strFileName.Replace(c, '_');
TECH_NETAuthor Commented:
I am using 1.1 and the error is thrown at strFileName = strFileName.Replace(":", "_");
In .Net 1.1:

strFileName = strFileName.Replace(Path.AltDirectorySeparatorChar, '_');
strFileName = strFileName.Replace(Path.DirectorySeparatorChar, '_');
strFileName = strFileName.Replace(Path.PathSeparator, '_');
strFileName = strFileName.Replace(Path.VolumeSeparatorChar, '_');
foreach (char c in Path.InvalidPathChars)
      strFileName = strFileName.Replace(c, '_');

Use chars (surrounded by 'apostrophes', not strings surrounded by "quotes"). If strFileName.Replace is throwing an error, you are changing strFileName from a string to something else; string.Replace has been in .Net since 1.0.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now