2017-10-17 128 views
0

我想訪問SD卡文件並讀取文件的所有內容。首先我不能寫SD卡插入我的電腦的路徑,因爲SD卡的名稱可以更改。除此之外,我想在我的目錄路徑中獲取所有文件名。SD卡目錄

目錄中的文件太多,它們以數字命名,如「1.txt」,「2.txt」。但我必須訪問最後一個文件並閱讀最後一個文件行。我正在使用下面的代碼。有任何建議嗎?

public void readSDcard() 
     {   
      //here i want to get names all files in the directory and select the last file 
      string[] fileContents;   

      try 
      { 
       fileContents = File.ReadAllLines("F:\\MAX\\1.txt");// here i have to write any sd card directory path 

       foreach (string line in fileContents) 
       { 
        Console.WriteLine(line); 
       } 
      } 
      catch (FileNotFoundException ex) 
      { 
       throw ex; 
      } 
     } 

回答

3

.NET框架不提供一種方法來確定,其中驅動器是一個SD卡(我懷疑有一個可靠的方式來做到這一點在所有的,至少在沒有非常低級的progaming,如查詢系統驅動程序)。你可以做的最好的是檢查DriveInfoDriveType財產等於DriveType.Removable,但是這也將選擇所有閃存驅動器等

但即便如此,你需要一些其他的信息,選擇合適的SD卡(想想,有可能會在計算機中插入多個SD卡)。如果SD卡有卷標將始終相同,您可以使用它來選擇正確的驅動器。否則,您將不得不詢問用戶,他希望使用哪個可移動驅動器,如下所示。

問題沒有說明,last file是什麼意思。它是上次創建的文件,上次修改的文件,操作系統枚舉的最後一個文件,還是文件名最大的文件?所以我假設你想要一個數量最大的文件。

public void readSDcard() 
{ 
    var removableDives = System.IO.DriveInfo.GetDrives() 
     //Take only removable drives into consideration as a SD card candidates 
     .Where(drive => drive.DriveType == DriveType.Removable) 
     .Where(drive => drive.IsReady) 
     //If volume label of SD card is always the same, you can identify 
     //SD card by uncommenting following line 
     //.Where(drive => drive.VolumeLabel == "MySdCardVolumeLabel") 
     .ToList(); 

    if (removableDives.Count == 0) 
     throw new Exception("No SD card found!"); 

    string sdCardRootDirectory; 

    if(removableDives.Count == 1) 
    { 
     sdCardRootDirectory = removableDives[0].RootDirectory.FullName; 
    } 
    else 
    { 
     //Let the user select, which drive to use 
     Console.Write($"Please select SD card drive letter ({String.Join(", ", removableDives.Select(drive => drive.Name[0]))}): "); 
     var driveLetter = Console.ReadLine().Trim(); 
     sdCardRootDirectory = driveLetter + ":\\"; 
    } 

    var path = Path.Combine(sdCardRootDirectory, "MAX"); 

    //Here you have all files in that directory 
    var allFiles = Directory.EnumerateFiles(path); 

    //Select last file (with the greatest number in the file name) 
    var lastFile = allFiles 
     //Sort files in the directory by number in their file name 
     .OrderByDescending(filename => 
     { 
      //Convert filename to number 
      var fn = Path.GetFileNameWithoutExtension(filename); 
      if (Int64.TryParse(fn, out var fileNumber)) 
       return fileNumber; 
      else 
       return -1;//Ignore files with non-numerical file name 
     }) 
     .FirstOrDefault(); 

    if (lastFile == null) 
     throw new Exception("No file found!"); 

    string[] fileContents = File.ReadAllLines(lastFile); 

    foreach (string line in fileContents) 
    { 
     Console.WriteLine(line); 
    } 
} 
相關問題