从文件名中删除特殊字符 [英] Remove Special characters from file name

查看:120
本文介绍了从文件名中删除特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从文件中删除特殊字符,我根据此示例,它生成的错误很少.我需要此代码才能用于基于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_. ]+", "");
        }
    }
}

&上的示例代码输出 ideone.com

Sample code on & output ideone.com

推荐答案

您已将私有静态字符串GetValidFileName 放在 public static void Main()中,而在C#中不是允许的.只需简单地更改代码即可,如下所示:

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);
    }
}

这篇关于从文件名中删除特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆