簡體   English   中英

檢查任意字符串是否為有效文件名的最簡單方法

[英]Easiest way to check if an arbitrary String is a valid filename

在我的應用程序中,用戶可以輸入文件名。 在處理之前,我想檢查輸入字符串是否是 Windows Vista 上的有效文件名。

最簡單的方法是什么?

通過有效,我指的是合法的和不存在的

檢查filename.IndexOfAny(Path.GetInvalidFileNameChars()) < 0!File.Exists(Path.Combine(someFolder, filename))

檢查GetInvalidFileNameChars()

var isValid = !string.IsNullOrEmpty(fileName) &&
              fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 &&
              !File.Exists(Path.Combine(sourceFolder, fileName));

如果要創建文件,您應該使用文件對話框來指定目錄路徑。 文件名有一個非法字符的簡短列表。

判斷文件名是否可接受的唯一真正可靠的方法是嘗試它。 權限是一個泥潭。

我用這個:

public static bool IsValidFileName(string name) {
    if(string.IsNullOrWhiteSpace(name)) return false;
    if(name.Length > 1 && name[1] == ':') {
        if(name.Length < 4 || name.ToLower()[0] < 'a' || name.ToLower()[0] > 'z' || name[2] != '\\') return false;
        name = name.Substring(3);
    }
    if(name.StartsWith("\\\\")) name = name.Substring(1);
    if(name.EndsWith("\\") || !name.Trim().Equals(name) || name.Contains("\\\\") ||
        name.IndexOfAny(Path.GetInvalidFileNameChars().Where(x=>x!='\\').ToArray()) >= 0) return false;
    return true;
}

應該處理除保留名稱、權限和長度限制之外的所有事情。 這接受相對和絕對文件名。

這只是一個想法。 應該填寫例外列表:

public static bool IsValidFilename(string filename)
{
    try
    {
        File.OpenRead(filename).Close();
    }
    catch (ArgumentException) { return false; }
    catch (Exception) { }
    return true;
}

對於第一部分(有效文件名),我使用所有方法和臨時文件創建來檢查文件是否可以按預期命名或引發異常。
在某些情況下,創建文件不會引發異常,直到嘗試刪除它(例如: CON )。
我還removePath arg 來指示文件只是沒有路徑的文件名。

using System.IO;
using System.Text;
private static readonly byte[] TestFileBytes = Encoding.ASCII.GetBytes(@"X");
public bool IsFileNameValid(string file, bool removePath = false)
{
    try
    {
        if (string.IsNullOrEmpty(file))
            return false;

        string fileNamePart = removePath ? Path.GetFileName(file) : file;
        if (fileNamePart.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
            return false;

        string fileName = Path.Combine(Path.GetTempPath(), fileNamePart);
        using FileStream fileStream = File.Create(fileName);
        {
            fileStream.Write(TestFileBytes, 0, TestFileBytes.Length);
        }

        File.Delete(fileName);
        return true;
    }
    catch
    {
        return false;
    }
}

如果拒絕訪問臨時文件夾,請使用自定義文件夾來創建測試文件。

此方法將導致false . or .. or ... r Windows 中的任何僅點名稱序列,您也不能手動創建它們,但這些實際上不是無效名稱! 這些是無法創建的文件名稱或類似名稱;)。

對於下一部分(不存在),只需使用: !File.Exists(yourFileNameWithPath)

如果為文件創建 DirectoryInfo,如果文件/目錄名稱有任何問題(無效字符或長度),它將引發異常。

DirectoryInfo di = new DirectoryInfo(myFileName);
Console.WriteLine("This filename/path could be valid. The folder might not exist yet though.")
if(di.Exists)
    Console.WriteLine("This file already exist.")

它使用異常進行流控制並不是很好,但您可以確信它是正確的。 OTOH,如果您已經計划給調用代碼一個異常,那么任務就完成了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM