• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 473
  • 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.

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

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