在 C# 中检查文件名是否*可能*有效(不是它存在)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/422090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 02:48:41  来源:igfitidea点击:

In C# check that filename is *possibly* valid (not that it exists)

c#validationfile

提问by

Is there a method in the System.IO namespace that checks the validity of a filename?

System.IO 命名空间中是否有检查文件名有效性的方法?

For example, C:\foo\barwould validate and :"~-*would not

例如,C:\foo\bar会验证,:"~-*不会

Or a little trickier, X:\foo\barwould validate is there is an X:drive on the system, but wouldn't otherwise.

或者有点棘手,X:\foo\bar会验证系统上是否有X:驱动器,否则不会。

I suppose I could write such a method myself, but I'm more interested in a built-in one.

我想我可以自己编写这样的方法,但我对内置方法更感兴趣。

回答by Eugene Katz

You can get a list of invalid characters from Path.GetInvalidPathCharsand GetInvalidFileNameCharsas discussed in this question.

本问题所述,您可以从Path.GetInvalidPathCharsGetInvalidFileNameChars获取无效字符列表

As noted by jberger, there some other characters which are not included in the response from this method. For much more details of the windows platform, take a look at Naming Files, Paths and Namespaceson MSDN,

正如 jberger 所指出的,还有一些其他字符未包含在此方法的响应中。有关 windows 平台的更多详细信息,请查看MSDN上的命名文件、路径和命名空间

As Micah points out, there is Directory.GetLogicalDrivesto get a list of valid drives.

正如 Micah指出的那样Directory.GetLogicalDrives可以获取有效驱动器的列表。

回答by mmmmmmmm

Just do;

做就是了;

System.IO.FileInfo fi = null;
try {
  fi = new System.IO.FileInfo(fileName);
}
catch (ArgumentException) { }
catch (System.IO.PathTooLongException) { }
catch (NotSupportedException) { }
if (ReferenceEquals(fi, null)) {
  // file name is not valid
} else {
  // file name is valid... May check for existence by calling fi.Exists.
}

For creating a FileInfoinstance the file does not need to exist.

对于创建FileInfo实例,该文件不需要存在。

回答by casperOne

Use the static GetInvalidFileNameCharsmethodon the Pathclassin the System.IOnamespaceto determine what characters are illegal in a file name.

命名空间中使用静态GetInvalidFileNameChars方法来确定文件名中哪些字符是非法的。PathSystem.IO

To do so in a path, call the static GetInvalidPathCharsmethodon the same class.

要在路径中执行此操作,请在同一类上调用静态GetInvalidPathChars方法

To determine if the root of a path is valid, you would call the static GetPathRootmethodon the Pathclass to get the root, then use the Directoryclassto determine if it is valid. Then you can validate the rest of the path normally.

要确定路径的根是否有效,您可以调用类上的静态GetPathRoot方法Path来获取根,然后使用Directory该类来确定它是否有效。然后您可以正常验证路径的其余部分。

回答by Michael Haren

Even if the filename is valid, you may still want to touchit to be sure the user has permission to write.

即使文件名有效,您可能仍然希望touch它确保用户具有写入权限。

If you won't be thrashing the disk with hundreds of files in a short period of time, I think creating an empty file is a reasonable approach.

如果您不会在短时间内用数百个文件来处理磁盘,我认为创建一个空文件是一种合理的方法。

If you really want something lighter, like just checking for invalid chars, then compare your filename against Path.GetInvalidFileNameChars().

如果你真的想要更轻松的东西,比如检查无效字符,那么将你的文件名与 Path.GetInvalidFileNameChars() 进行比较。

回答by tanathos

Probably the bast way is to build a custom method mixing a combination of regex and small look up on your file system (to see the drives, for example)

可能最糟糕的方法是构建一个自定义方法,混合使用正则表达式和文件系统上的小型查找(例如,查看驱动器)

回答by BFree

I don't know of anything out of the box that can just validate all of that for you, however the Pathclass in .NETcan help you out tremendously.

我不知道有什么开箱即用的东西可以为您验证所有这些,但是里面的Path课程.NET可以极大地帮助您。

For starters, it has:

首先,它有:

char[] invalidChars = Path.GetInvalidFileNameChars(); //returns invalid charachters

or:

或者:

Path.GetPathRoot(string); // will return the root.

回答by shackett

Several of the System.IO.Path methods will throw exceptions if the path or filename is invalid:

如果路径或文件名无效,几个 System.IO.Path 方法将抛出异常:

  • Path.IsPathRooted()
  • Path.GetFileName()
  • Path.IsPathRooted()
  • Path.GetFileName()

http://msdn.microsoft.com/en-us/library/system.io.path_methods.aspx

http://msdn.microsoft.com/en-us/library/system.io.path_methods.aspx

回答by Micah

There are several methods you could use that exist in the System.IOnamespace:

您可以使用System.IO命名空间中存在的几种方法:

Directory.GetLogicalDrives() // Returns an array of strings like "c:\"
Path.GetInvalidFileNameChars() // Returns an array of characters that cannot be used in a file name
Path.GetInvalidPathChars() // Returns an array of characters that cannot be used in a path.

As suggested you could then do this:

按照建议,您可以执行以下操作:

bool IsValidFilename(string testName) {
    string regexString = "[" + Regex.Escape(Path.GetInvalidPathChars()) + "]";
    Regex containsABadCharacter = new Regex(regexString);
    if (containsABadCharacter.IsMatch(testName)) {
        return false;
    }

    // Check for drive
    string pathRoot = Path.GetPathRoot(testName);
    if (Directory.GetLogicalDrives().Contains(pathRoot)) {
        // etc
    }

    // other checks for UNC, drive-path format, etc

    return true;
}

回答by Austin Salonen

This will get you the drives on the machine:

这将为您提供机器上的驱动器:

System.IO.DriveInfo.GetDrives()

These two methods will get you the bad characters to check:

这两种方法会让你检查坏字符:

System.IO.Path.GetInvalidFileNameChars();
System.IO.Path.GetInvalidPathChars();

回答by Jay Riggs

I've had luck using regular expressions as others have shown.

正如其他人所展示的那样,我很幸运地使用了正则表达式。

One thing to keep in mind is that Windows at least prohibits some filenames that otherwise containlegal characters. A few come to mind: com, nul, prn.

要记住的一件事是,Windows 至少禁止某些包含合法字符的文件名。我想到了几个:com、nul、prn。

I don't have it with me now, but I have a regex that takes these filename into consideration. If you want I can post it, otherwise I'm sure you can find it the same way I did: Google.

我现在没有它,但我有一个正则表达式将这些文件名考虑在内。如果你愿意,我可以发布它,否则我相信你可以像我一样找到它:谷歌。

-Jay

-杰