gpt4 book ai didi

C#:读取文件夹中的下一个文件?

转载 作者:行者123 更新时间:2023-11-30 20:34:37 27 4
gpt4 key购买 nike

我有一个包含 .txt 文件的文件夹,这些文件的编号如下:

0.txt
1.txt
...
867.txt
...

我想做的是每次调用 readNextFile(); 时,我希望它返回该文件夹中下一个文件的内容,并且 return string.Empty; 如果在它读取的最后一个文件之后没有文件。 我想要一个按钮,当按下该按钮时,程序将读取下一个文件并对其内容进行操作。这些文件可能会在按下按钮之间发生变化。我之前这样做的方式是这样的:

int lastFileNumber = 0;

string readNextFile()
{
string result = string.Empty;
//I know it is recommended to use as few of these as possible, this is just an example.
try
{
string file = Path.Combine("C:\Somewhere", lastFileNumber.ToString() + ".txt");
if (File.Exists(file))
{
result = File.ReadAllText(file);
lastFileNumber++;
}
}
catch
{

}
return result;
}

问题是有时可能会出现这种情况:

0.txt
1.txt
5.txt
6.txt
...

它显然会卡在 1.txt 处,因为 2.txt 不存在。我需要它跳到下一个现有文件并阅读那个文件。很明显,不可能仅按字母顺序对字符串数组中的文件名进行排序,因为文件名未填充,因此这样做将导致读取 1000000000.txt1.txt 之后。

知道如何实现吗?

最佳答案

您可以使用 linq 根据存储的编号检查下一个文件。这是在通过将文件名称转换为整数表示形式对文件进行排序后完成的:

int lastFileNumber = -1;
bool isFirst = true;
private void buttonNext_Click(object sender, EventArgs e)
{
int lastFileNumberLocal = isFirst ? -1 : lastFileNumber;
isFirst = false;
int dummy;
var currentFile = Directory.GetFiles(@"D:\", "*.txt", SearchOption.TopDirectoryOnly)
.Select(x => new { Path = x, NameOnly = Path.GetFileNameWithoutExtension(x) })
.Where(x => Int32.TryParse(x.NameOnly, out dummy))
.OrderBy(x => Int32.Parse(x.NameOnly))
.Where(x => Int32.Parse(x.NameOnly) > lastFileNumberLocal)
.FirstOrDefault();

if (currentFile != null)
{
lastFileNumber = Int32.Parse(currentFile.NameOnly);

string currentFileContent = File.ReadAllText(currentFile.Path);
}
else
{
// reached the end, do something or show message
}
}

关于C#:读取文件夹中的下一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38941428/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com