這一節(jié)來(lái)看看獲取文件屬性吧,可以獲取到文件名、類型、最近訪問(wèn)時(shí)間等等屬性。
下面這段代碼呢,都很簡(jiǎn)單。
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Width="200" Height="70" Name="btnGetProp" Content="獲取文件屬性" Click="btnGetProp_Click"/>
<TextBlock Name="tBlockProp" Margin="12" Width="480" FontSize="30"/>
</StackPanel>
</Grid>
</Page>
在 Click 事件中,先獲取到圖片庫(kù),當(dāng)然了,你可以獲取其他地方,我電腦上的庫(kù)文件中,就只有文檔庫(kù)和圖片庫(kù)有文件了。然后創(chuàng)建一個(gè)文件查詢,最后將這些文件都賦給 files。這里的 var 可謂是非常的強(qiáng)大啊。實(shí)例化一個(gè) StringBuilder 對(duì)象來(lái)輔助輸出信息那真是太完美不過(guò)了,我們?cè)谇懊嬉渤S玫剿?/p>
var folder = KnownFolders.PicturesLibrary;
var fileQuery = folder.CreateFileQuery();
var files = await fileQuery.GetFilesAsync();
StringBuilder fileProperties = new StringBuilder();
for (int i = 0; i < files.Count; i++)
{
StorageFile file = files[i];
fileProperties.AppendLine("File name: " + file.Name);
fileProperties.AppendLine("File type: " + file.FileType);
BasicProperties basicProperties = await file.GetBasicPropertiesAsync();
string fileSize = string.Format("{0:n0}", basicProperties.Size);
fileProperties.AppendLine("File size: " + fileSize + " bytes");
fileProperties.AppendLine("Date modified: " + basicProperties.DateModified);
fileProperties.AppendLine(" ");
}
tBlockProp.Text = fileProperties.ToString();
這樣一來(lái)就完成對(duì) Name、FileType、Size 和 DateModified 屬性的獲取,但還有一類屬性,則比較難以獲取,它們就是“擴(kuò)展屬性”。
List<string> propertiesName = new List<string>();
propertiesName.Add("System.DateAccessed");
propertiesName.Add("System.FileOwner");
IDictionary<string, object> extraProperties = await file.Properties.RetrievePropertiesAsync(propertiesName);
var propValue = extraProperties[dateAccessedProperty];
if (propValue != null)
fileProperties.AppendLine("Date accessed: " + propValue);
propValue = extraProperties[fileOwnerProperty];
if (propValue != null)
fileProperties.AppendLine("File owner: " + propValue);
最后將 fileProperties 傳遞給 TextBlock 即可。
tBlockProp.Text = fileProperties.ToString();
最后調(diào)試 App,就會(huì)像下圖一樣了。
但是如你所見(jiàn),文件名太長(zhǎng)了卻無(wú)法自動(dòng)換行,而且數(shù)據(jù)也顯示不完整。改改 XAML 中的 TextBlock 即可。TextWrapping 屬性設(shè)置為 Wrap,則可以換行;將 TextBlock 添加到 ScrollViewer 內(nèi)則會(huì)顯示出一個(gè)滾動(dòng)條。
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Width="200" Height="70" Name="btnGetProp" Content="獲取文件屬性" Click="btnGetProp_Click"/>
<ScrollViewer>
<TextBlock Name="tBlockProp" Margin="12" Width="480" FontSize="30" TextWrapping="Wrap"/>
</ScrollViewer>
</StackPanel>
</Grid>
更多建議: