我有一个应用程序,它读取名为“words.csv”的CSV文件。我的新要求是1)它需要确保在读取之前目录中只有一个CSV文件。 2)它应该读取任何带有“.CSV”扩展名的文件而不仅仅是“words.csv”(满足条件1之后)。希望这有道理吗? 有人可以帮忙吗?
public class VM
{
public VM()
{
Words = LoadWords(fileList[0]);
}
public IEnumerable<string> Words { get; private set; }
string[] fileList = Directory.GetFiles(@"Z:\My Documents\", "*.csv");
private static IEnumerable<string> LoadWords(String fileList)
{
List<String> words = new List<String>();
if (fileList.Length == 1)
{
try
{
foreach (String line in File.ReadAllLines(fileList))
{
string[] rows = line.Split(',');
words.AddRange(rows);
}
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.Message);
}
return words;
}
}
}
答案 0 :(得分:6)
您可以使用此代码获取文件夹中所有csv文件的列表:
string[] fileList = Directory.GetFiles( @"Z:\My Documents\", "*.csv");
所以为了满足你的条件,这应该可以解决问题:
string[] fileList = Directory.GetFiles( @"Z:\My Documents\", "*.csv");
if( fileList.Length == 1 )
{
//perform your logic here
}
答案 1 :(得分:1)
DirectoryInfo di = new DirectoryInfo(@"Z:\My Documents");
// Get a reference to each file in that directory.
FileInfo[] fiArr = di.GetFiles();
if(fiArr.Length ==1)
{
FileInfo fri = fiArr[0];
//use fri.Extension to check for csv
//process as required
}
答案 2 :(得分:0)
FileInfo file = new DirectoryInfo(@"Z:\My Documents")
.EnumerateFiles("*.csv")
.SingleOrDefault();
if (file != null)
{
//do your logic
}
Linq的SingleOrDefault运算符将确保具有给定模式的确切onle文件,否则它将返回null