Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Special characters from file name

Tags:

c#

asp.net

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

like image 730
Learning Avatar asked Oct 14 '14 08:10

Learning


1 Answers

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);
    }
}
like image 156
Tinwor Avatar answered Sep 30 '22 20:09

Tinwor