Link to home
Create AccountLog in
Avatar of mhdi
mhdi

asked on

C# file writing - Mixing StreamWriter and FileStream

Hi,

Someone (not me) has written this code. I am a beginner and dont understand. It seems to work, but it doesn't look right.

Can anyone explain why a StreamWriter is wrapped in a FileStream?

What is the best way to do this?

static public void Write(string message, string outputFile)
{
	lock (locker_output)
	{
		CheckAndCreateDirectory(outputFile);

		if (!File.Exists(outputFile))
		{
			// Create a file to write to.
			using (FileStream fs = new FileStream(outputFile, FileMode.OpenOrCreate, FileSystemRights.AppendData,
				FileShare.Write, 4096, FileOptions.None))
			{
				using (StreamWriter sw = new StreamWriter(fs)) 
				{
					AddTextAndFlush(message, sw);
				}
			}

			return;
		}
		// using existing
		using (FileStream fs = new FileStream(outputFile, FileMode.Open, FileSystemRights.AppendData,
			FileShare.Write, 4096, FileOptions.None))
		{
			using (StreamWriter sw = new StreamWriter(fs)) 
			{
				AddTextAndFlush(message, sw);
			}
		}
	}
}

Open in new window

SOLUTION
Avatar of Wim_Bl
Wim_Bl
Flag of Belgium image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of mhdi
mhdi

ASKER

Thanks for the info.

However is there any reason why you would wrap a StreamWriter inside a FileStream like my attached code?
A Stream always works on byte level, so it can write any type of data, including non-text. A StreamWriter can only work with plain text, although it does convert it into bytes in the background. So in your case it's just a little overshooting in my opinion.
Hi mhdi,

Both FileStream and StreamWriter implements IDisposable interface. So instead of calling the Dispose method explicitly, you can use the "using" keyword which dispose the object when already out of context. When we re-write the code, something like this

            FileStream fs = new FileStream(outputFile, FileMode.Open, FileSystemRights.AppendData, FileShare.Write, 4096, FileOptions.None);
            StreamWriter sw = new StreamWriter(fs);
            AddTextAndFlush(message, sw);
            fs.Dispose();
            sw.Dispose();

Open in new window

Avatar of mhdi

ASKER

@drypz: Is there a benefit using your method over using a FilStream by itself (completley removing the streamwriter)?
ASKER CERTIFIED SOLUTION
Avatar of Daniel Van Der Werken
Daniel Van Der Werken
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Hi,

Since you are getting the same result, so it depends upon your preference. Also, you may want to look at this [using] statement
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account