开发者

Dumping to Console works like a charm, but not to a file, C#

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


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


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)


Your r object is holding it open.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜