从文件名中删除特殊字符

7

我需要从文件中去除特殊字符,我尝试了以下基于这个例子的代码,但它会产生一些错误。我需要这段代码适用于基于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_. ]+", "");
        }
    }
}

ideone.com上,有与输出相关的示例代码。


实际上生成了哪些错误? - Codor
错误在这里列出 http://ideone.com/FzpqfC - Learning
1
https://dev59.com/Z2865IYBdhLWcg3wat6l#8626562 - Tim Schmelter
3个回答

14

您已将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);
    }
}

它有效了,但文件名中有空格“this isfilename.txt”,如何从文件名中移除空格? - Learning
我已经编辑了答案。我使用String.Replace而不是正则表达式来删除空格,因为它更易于阅读和理解。 - Tinwor

-1

试试这个:

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

-1

字符串 newName = UploadFile.FileName.Replace("&", "and");


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接