標籤:app開發 操作 顯示 軟體 資訊
在上一節中我們學習了資料繫結,因為我個人對上一篇還是比較滿意的,至少相對於前面的那些而言(我也知道前面寫的太差了,後面還會繼續修改的,部落格也像軟體一樣嘛)。這一節開始我們將陸續看到Windows App是怎樣操作檔案的。
在Windows上讀取檔案名稱、檔案夾名
首先我們在XAML中定義一個Button和TextBlock,將讀取檔案/檔案夾名的過程寫在前者的click事件中,後者則用來顯示檔案資訊。
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <StackPanel Orientation="Horizontal"> <Button Name="btnGetName" Width="200" Height="100" Content="讀取檔案名稱" Click="btnGetName_Click"/> <TextBlock Name="textBlockFileName" Width="500" Height="300" FontSize="30" Margin="12"/> </StackPanel> </Grid>
以下這段代碼,首先通過StorageFolder類讀取圖片庫,然後使用非同步方式將圖片庫的檔案和檔案夾資訊載入相應的List中。建立一個StringBuilder用以儲存這些檔案的資訊,在這裡只是使用了檔案/檔案夾的Name屬性,但屬性還有很多,比如Path屬性。最後再將這些擷取到的資訊賦值給TextBlock即可。
private async void btnGetName_Click(object sender, RoutedEventArgs e) { StorageFolder pictureFolder = KnownFolders.PicturesLibrary; IReadOnlyList<StorageFile> pictureFileList = await pictureFolder.GetFilesAsync(); IReadOnlyList<StorageFolder> pictureFolderList = await pictureFolder.GetFoldersAsync(); StringBuilder picutreFolderInfo = new StringBuilder(); foreach(StorageFile f in pictureFileList) { picutreFolderInfo.Append(f.Name+"\n"); } foreach(StorageFolder f in pictureFolderList) { picutreFolderInfo.Append(f.Name+"\n"); } textBlockFileName.Text = picutreFolderInfo.ToString(); }
注意要在方法名前面加上async哦。還有要在資訊清單檔中聲明我們的應用要使用圖片庫哦,一會在Windows Phone中也一樣。
在Windows Phone上讀取檔案名稱、檔案夾名
後台代碼不用做任何修改,只需把XAML代碼修改修改以適應螢幕即可~
<Grid> <StackPanel Orientation="Vertical"> <Button Name="btnGetName" Width="150" Height="70" HorizontalAlignment="Center" Content="讀取檔案名稱" Click="btnGetName_Click"/> <TextBlock Name="textBlockFileName" Width="300" Height="300" FontSize="30" Margin="12" TextWrapping="Wrap"/> </StackPanel> </Grid>
讀取檔案名稱的其他方法
private async void btnGetName_Click(object sender, RoutedEventArgs e) { StorageFolder picutureFolder = KnownFolders.PicturesLibrary; StringBuilder pictureFolderInfo = new StringBuilder(); IReadOnlyList<IStorageItem> pictureFileItem = await picutureFolder.GetItemsAsync(); foreach(var i in pictureFileItem) { if (i is StorageFolder) pictureFolderInfo.Append(i.Name + "\n"); else pictureFolderInfo.Append(i.Name + "\n"); } textBlockFileName.Text = pictureFolderInfo.ToString(); }
【萬裡征程——Windows App開發】檔案操作——讀取檔案