TheUnrealMegashark
TheUnrealMegashark

Reputation: 309

Edit text file after creation

I am creating a text file if it doesn't exist and then immediately after I am adding text to that file. However, my compiler says it's being used by another process, which I assume is because it was just created. How can I fix this?

Code excerpt-

//If the text document doesn't exist, create it
if (!File.Exists(set.cuLocation))
{
    File.CreateText(set.cuLocation);
}

//If the text file after being moved is empty, edit it to say the previous folder's name
System.IO.StreamReader objReader = new System.IO.StreamReader(set.cuLocation);
set.currentUser = objReader.ReadLine();
objReader.Close();
if (set.currentUser == null)
{
    File.WriteAllText(set.cuLocation, set.each2);
}

Upvotes: 0

Views: 198

Answers (3)

pcnThird
pcnThird

Reputation: 2372

You can enclose it in a using block which will automatically close the stream for you:

if (!File.Exists(set.cuLocation))
{
    File.CreateText(set.cuLocation);
}

using(System.IO.StreamReader objReader = new System.IO.StreamReader(set.cuLocation))
{
   set.currentUser = objReader.ReadLine();
}

if (set.currentUser == null)
{
    File.WriteAllText(set.cuLocation, set.each2);
}

Upvotes: 0

Konrad Morawski
Konrad Morawski

Reputation: 8394

CreateText method actually creates (and returns) a StreamWriter object. You're never closing that stream. What is it that you're trying to accomplish? Why do you attempt to read from an empty file? Just keep a reference to that StreamWriter you're creating and use it for writing.

StreamWriter sw = File.CreateText(set.cuLocation);

and then call sw.Write etc.

See http://msdn.microsoft.com/en-us/library/system.io.streamwriter.write.aspx for reference.

When you're done, call sw.Close.

Note that it could happen that an exception is thrown while you're writing. This could prevent the stream from being closed.

A good pattern that addresses this issue is to wrap the StreamWriter in a using block. See this question for more details: Is it necessary to wrap StreamWriter in a using block?

Upvotes: 5

oakio
oakio

Reputation: 1898

Don't forget call Close method:

if (!File.Exists(set.cuLocation))
{
    File.Create(set.cuLocation)
        .Close();
}

Upvotes: 1

Related Questions