如何确保文件名文件夹名字有效

windows的 文件夹或者文件名必须不包含一些字符,并且长度有一定的限制,下面的两个方法可以确保文件或者文件夹的名字有效。

static string MakeFilenameValid(string filename)
{
    if (filename == null)
        throw new ArgumentNullException();

    if (filename.EndsWith("."))
        filename = Regex.Replace(filename, @"\.+$", "");

    if (filename.Length == 0)
        throw new ArgumentException();

    if (filename.Length > 245)
        throw new PathTooLongException();

    foreach (char c in System.IO.Path.GetInvalidFileNameChars())
    {   
        filename = filename.Replace(c, '_');
    }
        
    return filename;
}

static string MakeFoldernameValid(string foldername)
{
    if (foldername == null)
        throw new ArgumentNullException();

    if (foldername.EndsWith("."))
        foldername = Regex.Replace(foldername, @"\.+$", "");

    if (foldername.Length == 0)
        throw new ArgumentException();
    
    if (foldername.Length > 245)
        throw new PathTooLongException();
    
    foreach (char c in System.IO.Path.GetInvalidPathChars())
    {
        foldername = foldername.Replace(c, '_');
    }

    return foldername;
}
http://blog.miniasp.com/post/2009/10/How-to-ensure-filename-and-foldername--is-valid.aspx
posted @ 2009-12-29 22:35  玉开  阅读(747)  评论(0编辑  收藏  举报