David Asssad
David Asssad

Reputation: 41

Why is the file not opening?

I can't get the file to open.

private void button1_Click(object sender, EventArgs e)
{
    // Load the CSV file
    var lines = File.ReadAllLines(@"C:\chat.csv");

    var xml = new XElement("Chat-Log",          // To convert to XML
       lines.Select(line => new XElement("Item",
          line.Split('|')                       // indicate split
          .Select((column, index) => new XElement("Column" + index, column)))));

    xml.Save(@"C:\xml-out.xml");     // Save to XML file

    MessageBox.Show("Converted to XML");

    FileStream fileStream = new FileStream(@"c:\xmlout.xml", FileMode.Open);
    try
    {
        TextWriter tw = new StreamWriter("c:\\xml-out.xml");
    }
    finally
    {
        fileStream.Close();
    }
}

The above piece of code should open C:\xml-out.xml, right?

 TextWriter tw = new StreamWriter("c:\\xml-out.xml");

I have no idea why it is not opening the file. Any clue?

I tried various options.

Upvotes: 0

Views: 135

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503260

For some reason, you're opening a stream and then trying to create a writer for it.

If the file didn't exist before, then the call to new FileStream(@"c:\xmlout.xml", FileMode.Open) will throw an exception... and if the file did exist before, then you won't be able to open a writer to it in the following line because you've still got the file open for reading. You're also then closing the FileStream in the finally block, but never closing the StreamWriter, which is odd.

I expect you've probably got an exception showing which of those is actually causing the problem, but you should certainly remove the statement for the FileStream.

You should use a using statement so you don't need an explicit try/finally block:

using (StreamWriter writer = File.CreateText(@"c:\xml-out.xml"))
{
}

Of course there's then the possibility that you don't have permission to create a file on the root of the file system...

Upvotes: 3

Related Questions