Ben
Ben

Reputation: 1153

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

Upvotes: 2

Views: 8176

Answers (3)

Nasmi Sabeer
Nasmi Sabeer

Reputation: 1380

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

Upvotes: 0

MattC
MattC

Reputation: 4004

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

Upvotes: 1

&#216;yvind Br&#229;then
&#216;yvind Br&#229;then

Reputation: 60694

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
}

Upvotes: 6

Related Questions