7

I need to remove special characters from file, I tried following code based on this example, it is generating few errors. I need this code to work for asp.net webform based application.

using System;
using System.Linq;
using System.Text.RegularExpressions;

public class Test {
    public static void Main() {
        // your code goes here

        var file_name = GetValidFileName("this is)file<ame.txt");
        Console.WriteLine(file_name);
        private static string GetValidFileName(string fileName) {
            // remove any invalid character from the filename.
            return Regex.Replace(fileName.Trim(), "[^A-Za-z0-9_. ]+", "");
        }
    }
}

Sample code on & output ideone.com

Learning
  • 19,469
  • 39
  • 180
  • 373

3 Answers3

14

You have put private static string GetValidFileName in public static void Main() and in C# is not allowed. Just simple change the code as follow and it will work:

using System;
using System.Linq;
using System.Text.RegularExpressions;

public class Test {
    public static void Main() {
    // your code goes here

    var file_name = GetValidFileName("this is)file<ame.txt");
    Console.WriteLine(GetValidFileName(file_name));

    }
    private static string GetValidFileName(string fileName) {
        // remove any invalid character from the filename.
        String ret = Regex.Replace(fileName.Trim(), "[^A-Za-z0-9_. ]+", "")
        return ret.Replace(" ", String.Empty);
    }
}
Tinwor
  • 7,765
  • 6
  • 35
  • 56
  • It worked but file have has white space `this isfileame.txt` how can i remove white space from file name. – Learning Oct 14 '14 at 08:40
  • Edited answer. I've used String.Replace instead of regex to remove whitespace only because it's more easy and readble – Tinwor Oct 14 '14 at 08:44
-1

string newName = UploadFile.FileName.Replace("&", "and");

-1

Try this:

Console.WriteLine("Type a File Name:");
char[ ] invalidChars = System.IO.Path.GetInvalidFileNameChars();

string? FileName = Console.ReadLine();
if( FileName != null )
{
   string OutputFileName="";
   
   for (int i = 0; i < FileName.Length; i++)
   {
      char c = FileName[i];

      if (! invalidChars.Contains(c))
      {
         OutputFileName += c;
      }
   }
   Console.WriteLine("Output :");
   Console.WriteLine(OutputFileName);
}
JJDiez
  • 1
  • 1