2012-06-20 21 views
5

C# programımda dizinlere göz atmam gerekiyor. Bu yüzden System.IO.Directory.GetFiles(directory) yöntemini kullanıyorum ve dizin "C: \ Program Dosyası" gibi gerçek bir dizin olduğunda iyi çalışır, ancak sanal bir dizin olduğunda (örn: librairie dizini), dizin değeri şu şekilde görünür: ":: {031E4825 -7B94-4dc3-B131-E946B44C8DD5} \ Pictures.library-ms "ve nasıl göz atılacağını bilmiyorum.C# içindeki yerel bir sanal klasöre nasıl göz atabilirim?

cevap

1

Fiziksel bir birine sanal yolunu çevirmek gerekir, deneyin:

DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath("your virtual folder here")); 

Sen DirectoryInfo hakkında bilgi edinmek isteyebilirsiniz. O yaramaz, bu bir yerine bu deneyin: Bu bakarak geçmiş yarım gün boyunca anladım ne

DirectoryInfo info = new DirectoryInfo("virtual folder here"); 
FileInfo[] files = info.GetFiles("*.*", SearchOption.AllDirectories); 
+0

"Server.MapPath" nedir? MapPath için bulabildiğim MSDN referansları hepsi System.Web içinde ... OP bu bir web uygulaması olduğunu belirtmedi, ayrıca, açıklamadan web gibi bir şey göründü. – poncha

+1

'OP bunun bir web uygulaması olduğunu belirtmedi. Ya da öyle olmadığını belirtmedi ... – dtsg

+1

Haklısın, o yapmadı, ama vermiş olduğu belirli örnek şüphesiz web ile ilgili olan bir sistem kütüphanesi için sanal bir yoldu ... – poncha

1

bu yaşlı çılgın olduğunu biliyorum ama durumda birileri çözüm istiyor, burada . Orada size the folder names if you give it the path to the Virtual Folder's XML location elde edebilirsiniz birkaç çözüm vardır, ama gördüğüm hiçbir şey orada ::{031E4825-....} alır. WindowsAPICodePack'in KnownFoldersBrowser örneğini kullanmak için hint in another question's answer vardı. Bu yüzden bu kaynak kodu okumak ve aşağıdaki ile geldi: İşte

Ben klasörleri almak için kullanıyordum DialogBox edilir ve ben izin verir AllowNonFileSystemItems, Kütüphane klasör seçimleri için etkin:

Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog dlg = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog(); 
dlg.Title = "Pick Folder"; 
dlg.IsFolderPicker = true; 
dlg.InitialDirectory = Environment.SpecialFolder.Personal.ToString(); // If default setting does not exist, pick the Personal folder 

dlg.AddToMostRecentlyUsedList = false; 
dlg.AllowNonFileSystemItems = true; 
dlg.DefaultDirectory = dlg.InitialDirectory; 
dlg.EnsurePathExists = true; 
dlg.EnsureFileExists = false; 
dlg.EnsureReadOnly = false; 
dlg.EnsureValidNames = true; 
dlg.Multiselect = true; 
dlg.ShowPlacesList = true; 

if (dlg.ShowDialog() == Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult.Ok) 
{ 
    foreach (string dirname in dlg.FileNames) 
    { 
     var libFolders = ExpandFolderPath(dirname); 
     if (libFolders == null) 
     { 
      MessageBox.Show("Could not add '" + dirname + "', please try another."); 
     } 
     else 
     { 
      foreach (string libfolder in libFolders) 
      { 
       DoWork(libfolder); 
      } 
     } 
    } 
} 

Ardından, ::{031E4825-...}'u SpecialFolder için ParsingName olan allSpecialFolders üzerinde yineliyorum (evet, muhtemelen daha zarif bir yol). Bundan sonra, o kütüphane klasöründeki klasörleri almak için başka çözümler (I used a CodeProject example that did the same thing) okuma XML kullanın:

/// <summary>Gets the folders associated with a path</summary> 
    /// <param name="libname"></param> 
    /// <returns>Folder, or List of folders in library, and null if there was an issue</string></returns> 
    public List<string> ExpandFolderPath(string foldername) 
    { 
     List<string> dirList = new List<string> { }; 
     // If the foldername is an existing directory, just return that 
     if (System.IO.Directory.Exists(foldername)) 
     { 
      dirList.Add(foldername); 
      return dirList; 
     } 

     // It's not a directory, so check if it's a GUID Library folder 
     ICollection<IKnownFolder> allSpecialFolders = Microsoft.WindowsAPICodePack.Shell.KnownFolders.All; 
     Regex libguid = new Regex(@"\b([A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12})\b"); 
     var match = libguid.Match(foldername); 
     if (match == null) 
      return null; 

     string fpath = ""; 
     // Iterate over each folder and find the one we want 
     foreach (var folder in allSpecialFolders) 
     { 
      if (folder.ParsingName == foldername) 
      { 
       // We now have access to the xml path 
       fpath = folder.Path; 
       break; 
      } 
     } 
     if (fpath == "") 
     { 
      // Could not find it exactly, so find one with the same prefix, and 
      // replace the filename 
      foreach (var folder in allSpecialFolders) 
      { 
       if (folder.ParsingName.Contains(match.Groups[1].Value)) 
       { 
        string sameDir = System.IO.Path.GetDirectoryName(folder.Path); 
        string newPath = System.IO.Path.Combine(sameDir, match.Groups[2].Value); 
        if (System.IO.File.Exists(newPath)) 
         fpath = newPath; 
        break; 
       } 
      } 
     } 

     if (fpath == "") 
      return null; 

     var intFolders = GetLibraryInternalFolders(fpath); 

     return intFolders.Folders.ToList(); 

    } 


    /// <summary> 
    /// Represents an instance of a Windows 7 Library 
    /// </summary> 
    public class Win7Library 
    { 
     public Win7Library() 
     { 

     } 

     public string Name { get; set; } 

     public string[] Folders { get; set; } 
    } 

    [DllImport("shell32.dll")] 
    static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr pszPath); 

    //Handles call to SHGetKnownFolderPath 
    public static string getpathKnown(Guid rfid) 
    { 
     IntPtr pPath; 
     if (SHGetKnownFolderPath(rfid, 0, IntPtr.Zero, out pPath) == 0) 
     { 
      string s = System.Runtime.InteropServices.Marshal.PtrToStringUni(pPath); 
      System.Runtime.InteropServices.Marshal.FreeCoTaskMem(pPath); 

      return s; 
     } 
     else return string.Empty; 
    } 

    private static string ResolveStandardKnownFolders(string knowID) 
    { 
     if (knowID.StartsWith("knownfolder:")) 
     { 
      return getpathKnown(new Guid(knowID.Substring(12))); 
     } 
     else 
     { 
      return knowID; 
     } 
    } 

    private static Win7Library GetLibraryInternalFolders(string libraryXmlPath) 
    { 
     Win7Library newLibrary = new Win7Library(); 
     //The Name of a Library is just its file name without the extension 
     newLibrary.Name = System.IO.Path.GetFileNameWithoutExtension(libraryXmlPath); 

     List<string> folderpaths = new List<string>(); 

     System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); //* create an xml document object. 
     xmlDoc.Load(libraryXmlPath); //* load the library as an xml doc. 

     //Grab all the URL tags in the document, 
     //these point toward the folders contained in the library. 
     System.Xml.XmlNodeList directories = xmlDoc.GetElementsByTagName("url"); 

     foreach (System.Xml.XmlNode x in directories) 
     { 
      //Special folders use windows7 Know folders GUIDs instead 
      //of full file paths, so we have to resolve them 
      folderpaths.Add(ResolveStandardKnownFolders(x.InnerText)); 
     } 

     newLibrary.Folders = folderpaths.ToArray(); 
     return newLibrary; 
    } 

Umut bu gelecekte birisi yardımcı olur!

+1

Alternatif olarak, ['Shell.Application.NameSpace (" :: {031E4825 -....} ") .Items'] (http://blogs.msdn.com/b/oldnewthing /archive/2013/02/04/10390725.aspx). Yalnızca kitaplıkları arıyorsanız [Kitaplık API'sı] 'nı kullanabilirsiniz (https://msdn.microsoft.com/en-us/library/windows/desktop/dd758094 (v = vs.85) .aspx). – Mitch

İlgili konular