2016-05-31 62 views
0

如何刪除具有特定擴展名的文件?例如:.PDF無法刪除傳送帶上的文件

我試試這個代碼:

StorageFolder library = await installedLocation.CreateFolderAsync("library", CreationCollisionOption.OpenIfExists); 
BookAudio hapusmajalah = this.carousel.SelectedItem as BookAudio; 
try 
         { 
if(hapusmajalah.Name == hapusmajalah.Name + ".pdf") 
{ 
    StorageFile filepdf = await library.GetFileAsync(hapusmajalah.Name + ".pdf"); 

          await filepdf.DeleteAsync(); 
} 

          this.carousel.SelectedItem = carousel.Items[0]; 
          await this.getContent(); 

         } 
         catch 
         { 
          this.carousel.SelectedItem = carousel.Items[0]; 
          this.getContent(); 
         } 
        })); 
} 

BookAudio類:

class BookAudio 
    { 
     public string Name { get; set; } 

     public ImageSource Image { get; set; } 
    } 

,但沒有成功刪除。如果不使用if,則文件已成功刪除。如何解決這個問題呢?

回答

0

您可以使用path.getextension。

的參考文獻:

using System.Linq; 
using System.IO; 

和主代碼如下:

#region //Remove files with the extensions in the list. 
    public static void deleteFileExtensions(List<string> fileExtensionsToRemove, string filepath) 
    { 
     try 
     { 
      /*Get the extension by splitting by the final period.*/ 
      string tocompare = Path.GetExtension(filepath); 
      /*For every element in the list, if one of the extensions matches the file extension, delete*/ 
      fileExtensionsToRemove.ForEach(x => { if (tocompare.Contains(x)) File.Delete(filepath); }); 
     } 
     catch(IOException ex) { Console.WriteLine(ex); } 
    } 
    #endregion 

然後,你可以這樣調用它:

deleteFileExtensions(File.ReadAllLines("ExtensionsToDelete.txt").ToList(), "yourFilePath"); 
+0

什麼 「yourFilePath」 的意思嗎? 在我的項目文件「庫」StorageFolder – Rose