簡體   English   中英

使用C#,如何獲取包含Windows文件夾或文件的所有可用屬性的對象(或kv對數組)?

[英]Using C#, how do I get an object (or array of kv pairs) containing all available properties of a Windows folder or file?

我希望在不知道事先可用的屬性的情況下執行類似下面的偽代碼的操作:

foreach(var property in folder){
     var propertyName = property.Name;
     var propertyValue = property.Value;

     //do other stuff with the values.
}

我希望能夠對文件(而不是文件夾)也這樣做。

提前致謝。

嘗試DirectoryInfo.GetFiles(模式) 它返回一個FileInfo []數組,其中包含一些屬性,如名稱,文件屬性,創建日期,......

假設您正在討論諸如“只讀”,“隱藏”等屬性的類型,您可以執行以下操作來構建字典:

var dir = new DirectoryInfo(@"C:\temp");
var attributes = new Dictionary<string, bool>();
foreach (int value in Enum.GetValues(typeof (FileAttributes)))
{
    var attribute = (FileAttributes)value;
    var hasAttribute = dir.Attributes.HasFlag(attribute);
    attributes.Add(attribute.ToString(), hasAttribute);
}

attributes字典將包含目錄的可能屬性,以及一個布爾值,用於指示該屬性是否存在。

您可以使用FileInfo為文件而不是DirectoryInfo執行完全相同的操作。

最后,@ TimS關於這個鏈接的建議對我來說是最好的。 這是完整的代碼:

        var fileInfo = new FileInfo(folderPath);
        var folderProperties = fileInfo.GetType().GetProperties();
        foreach (var property in folderProperties)
        {
                var propName = property.Name
                var propValue = property.GetValue(fileInfo, null);

                //do stuff                                         
        }

暫無
暫無

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

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