我需要从文件中删除特殊字符,我尝试使用基于此example的代码,它产生的错误很少。我需要这段代码才能用于基于asp.net webform的应用程序。
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_. ]+", "");
}
}
}
示例代码&amp;输出ideone.com
答案 0 :(得分:6)
您已将private static string GetValidFileName
放入public static void Main()
并且不允许使用C#。只需简单地更改代码如下,它将起作用:
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);
}
}
答案 1 :(得分:-1)
string newName = UploadFile.FileName.Replace("&", "and");