tags:

views:

45

answers:

3

Consider this piece of code:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DataExtractor
{
    class Program
    {
        static void Main(string[] args)
        {
            string destpath = Directory.GetCurrentDirectory();
            destpath = Path.Combine(destpath, "DIR");
            DirectoryInfo Dest = Directory.CreateDirectory(destpath);
            DirectoryInfo Source = new DirectoryInfo(Directory.GetCurrentDirectory() + "\\IEOD");
            FileInfo[] fiArr = Source.GetFiles("*.csv");
            Console.WriteLine("Search Date:");
            string srchdate = Console.ReadLine();
            FileInfo r;
            foreach (FileInfo f in fiArr)
            {
                r = new FileInfo(Path.Combine(destpath,f.Name));
                r.Create();
                string path = Path.Combine(destpath, f.Name);
                string[] lines = File.ReadAllLines(f.FullName);
              var output = lines.Where(line => line.Split(',')[0] == srchdate);

                        try
                        {
                            //File.WriteAllLines(path, output.ToArray());
                            Console.WriteLine(output.ToArray());
                            Console.Write("\n");

                        }
                        catch(Exception ex)
                        {
                            Console.WriteLine(ex.StackTrace);
                        }


                }



            Console.ReadKey();


        }
    }
}

What is wrong with this piece of code? Inside the try block, the Console.WriteLine() works like a charm, but the commented line inside the try block, File.WriteAllLines(), is not working. The error message which comes up is, that the said file {} is being used by another process.

This is happening no matter what, if I use StreamWriter or File.WriteAllLines()

Help Appreciated. Soham

+1  A: 

You should remove the following lines:

    r = new FileInfo(Path.Combine(destpath,f.Name));
    r.Create();

You're creating the output file and leaving it open. The File.WriteAllLines() will create the file for you (and close it when done)

Philippe Leybaert
Wow! Thanks a lot! I suspected this issue but never thought Create() will leave the file open. Thanks
Soham
A: 

Your r object is holding it open.

Anton Gogolev
Thanks Anton, I didnt realise r.Create() will keep it open
Soham
A: 

File.WriteAllLines() creates, writes and closes the file, so you don't want the call to r.Create();

Dave Arkell