C# 从文件名中删除特殊字符
我需要从文件中删除特殊字符,我尝试了以下基于此的代码,它生成了一些错误。我需要这段代码来为基于asp.net Web表单的应用程序工作C# 从文件名中删除特殊字符,c#,asp.net,C#,Asp.net,我需要从文件中删除特殊字符,我尝试了以下基于此的代码,它生成了一些错误。我需要这段代码来为基于asp.net Web表单的应用程序工作 using System; using System.Linq; using System.Text.RegularExpressions; public class Test { public static void Main() { // your code goes here var file_name = Ge
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_. ]+", "");
}
}
}
使用系统;
使用System.Linq;
使用System.Text.RegularExpressions;
公开课考试{
公共静态void Main(){
//你的密码在这里
var file_name=GetValidFileName(“这是”)file您已将私有静态字符串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);
}
}
使用系统;
使用System.Linq;
使用System.Text.RegularExpressions;
公开课考试{
公共静态void Main(){
//你的密码在这里
var file_name=GetValidFileName(“这是”)filestring newName=UploadFile.FileName.Replace(“&”,“and”)实际生成的错误是什么?错误列在这里它起作用了,但文件有空格这是fileame.txt
如何从文件名中删除空格。编辑的答案。我使用了String.Replace而不是regex来删除空格,只是因为它更容易阅读