我想访问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;
}
}发布于 2017-10-17 15:05:00
.NET框架没有提供一种方法来识别哪个驱动程序是SD卡(我怀疑根本没有可靠的方法来做到这一点,至少没有非常低级别的progaming,例如查询系统驱动程序)。您可以做的最好是检查DriveType属性的DriveInfo是否等于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);
}
}https://stackoverflow.com/questions/46790606
复制相似问题