SORU
21 Kasım 2008, Cuma


C# Dosya Sterilize

Geçenlerde bir depo içine çeşitli yerlerden MP3 hareket eden bir sürü olmuştur. Yeni dosya adları İD3 etiketleri (teşekkürler, TagLib-Sharp!) kullanarak inşa edilmişti System.NotSupportedException bir alıyordum fark ettim:

"Verilen yolun biçimi desteklenmiyor."

Bu da File.Copy() Directory.CreateDirectory() ile oluşturulmuştur.

Uzun dosya isimleri dezenfekte edilmesi gerektiğini fark ettim. Açık bir şey yaptım:

public static string SanitizePath_(string path, char replaceChar)
{
    string dir = Path.GetDirectoryName(path);
    foreach (char c in Path.GetInvalidPathChars())
        dir = dir.Replace(c, replaceChar);

    string name = Path.GetFileName(path);
    foreach (char c in Path.GetInvalidFileNameChars())
        name = name.Replace(c, replaceChar);

    return dir   name;
}

Benim için sürpriz, istisnalar almaya devam ettim. Dışarı çıktı ':' yol bir kök içinde geçerli olduğundan Path.GetInvalidPathChars(), kümesinde değildir. Mantıklı - ama bu oldukça yaygın bir sorun olmalı diye düşünüyorum. Herkes bir yol ... ... temizlediği iddia ediliyor bazı kısa kod var mı? En kapsamlı ben bu ile geldi. ama muhtemelen overkill gibi geliyor.

    // replaces invalid characters with replaceChar
    public static string SanitizePath(string path, char replaceChar)
    {
        // construct a list of characters that can't show up in filenames.
        // need to do this because ":" is not in InvalidPathChars
        if (_BadChars == null)
        {
            _BadChars = new List<char>(Path.GetInvalidFileNameChars());
            _BadChars.AddRange(Path.GetInvalidPathChars());
            _BadChars = Utility.GetUnique<char>(_BadChars);
        }

        // remove root
        string root = Path.GetPathRoot(path);
        path = path.Remove(0, root.Length);

        // split on the directory separator character. Need to do this
        // because the separator is not valid in a filename.
        List<string> parts = new List<string>(path.Split(new char[]{Path.DirectorySeparatorChar}));

        // check each part to make sure it is valid.
        for (int i = 0; i < parts.Count; i  )
        {
            string part = parts[i];
            foreach (char c in _BadChars)
            {
                part = part.Replace(c, replaceChar);
            }
            parts[i] = part;
        }

        return root   Utility.Join(parts, Path.DirectorySeparatorChar.ToString());
    }

Bu fonksiyon daha hızlı ve daha az Barok yapmak için herhangi bir yenilik çok mutluluk duyacağız.

CEVAP
11 Mayıs 2009, PAZARTESİ


Bir dosya temizlemek için bunu yapmak olabilir adı

private static string MakeValidFileName( string name )
{
   string invalidChars = System.Text.RegularExpressions.Regex.Escape( new string( System.IO.Path.GetInvalidFileNameChars() ) );
   string invalidRegStr = string.Format( @"([{0}]*\. $)|([{0}] )", invalidChars );

   return System.Text.RegularExpressions.Regex.Replace( name, invalidRegStr, "_" );
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Joseph Herscher

    Joseph Hersc

    14 Mart 2007
  • Alexey - servant of Christ

    Alexey - ser

    15 EYLÜL 2007
  • Khan Academy

    Khan Academy

    17 Kasım 2006