开发者

C# Reading file in a directory

I have an app that reads a CSV file called “words.csv”. My new requirement is that 1) it needs to ensure that there is only one CSV file in the directory before reading. 2) It should read any file with ".CSV" extension not just “words.csv” (after condition 1 is satisfied). Hope this makes sense? Can anyone assist?

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<St开发者_如何转开发ring>();

        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;
        }
    }
}


You can use this code to get a list of all the csv files in a folder:

string[] fileList = Directory.GetFiles( @"Z:\My Documents\", "*.csv");

So to satisfy your conditions, this should do the trick:

string[] fileList = Directory.GetFiles( @"Z:\My Documents\", "*.csv");
if( fileList.Length == 1 )
{
  //perform your logic here
}


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
}

MSDN:DirectoryInfo.GetFiles

MSDN: FileInfo


FileInfo file = new DirectoryInfo(@"Z:\My Documents")
                            .EnumerateFiles("*.csv")
                            .SingleOrDefault();

if (file != null)
{
   //do your logic
}

Linq's SingleOrDefault operator will make sure there's exactly onle file with the given pattern otherwise it will return null

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜