tags:

views:

65

answers:

1

I have taken an example straight out of the MSDN. I want to create a file and write to it straight away. I was hoping to use FileInfo objects. So I create a new FileInfo object, call the Create and then open a FileStream. When I try to open the FileStream I get an exception telling me that another process is using the file. (Yes me).

I copy-pasted the MSDN example straight and their code suffers from the same thing. What have I/they done wrong? (P.S. .Net 3.5)

Update: The code below is STRAIGHT from the MSDN

    string path = @"c:\MyTest.txt";
    FileInfo fi = new FileInfo(path);

    if (!fi.Exists) 
    {
        //Create the file.
        fi.Create();
    }

    // Open the stream for writing.
    using (FileStream fs = fi.OpenWrite()) 
    {
        Byte[] info = 
            new UTF8Encoding(true).GetBytes("This is to test the OpenWrite method.");

        // Add some information to the file.
        fs.Write(info, 0, info.Length);
    }
+2  A: 

You are trying to open a file that is already open and locked, you need to call fi.Close() after your create if you are intending to reuse it as fi.Create() opens a filestream which allows you to read/write the file automatically. I believe by default Create() will just use an existing file if one already exists, so you could just use that to initialize your filestream.

For example

// Create a reference to a file.
FileInfo fi = new FileInfo("temp.txt");
// Actually create the file.
FileStream fs = fi.Create();
// Modify the file as required, and then close the file.
fs.Close();
// Delete the file.
fi.Delete();
dnolan
There is no Close method on the FileInfo. So I think not. This is also Microsoft's example.
uriDium
Ah, I see now. Thank you very much. That did it :)
uriDium
Please mark the answer as accepted if it solved your problem.
gehho