我已经搜索了大约一个小时,但还是找不到解决我问题的方法。除了以“_days.txt”结尾的文件之外,我正在尝试显示某个目录中的所有 .txt 文件。这是我的代码,希望你能有所帮助。谢谢!
foreach (FileInfo file in files)
{
if (file.Name.Substring(file.Length - 9, file.Length) != "_days.txt") //I get errors on this row, saying "Arg1, Arg2; Cannot convert from "long" to "int"
{
listBox1.Items.Add(file.Name);
}
}
最佳答案
要回答您最初的问题(并回答您收到错误的原因),您正在尝试使用针对 long File.Length
的操作结果。 (这是另一个问题,因为这是文件的大小,而不是文件名的长度)作为 string.Substring(int, int)
的参数.自 long
之间的操作以来和 int
将返回 long
(因为它是较大的类型),您需要将其转换为 int
首先——但是File.Length
无论如何都不是您想要的领域。
尝试使用 String.EndsWith(string) ,因为无论如何它都更具可读性。
foreach (FileInfo file in files)
{
if (!file.Name.EndsWith("_days.txt"))
{
listBox1.Items.Add(file.Name);
}
}
关于C# - 从 DirectoryInfo 中删除某些文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17029133/