I’ve just started using filestream, and although I made the code work,- I would really like to make it pretty as well 🙂 I have no idea where to place the using statements so I can skip the stream.Close(), and how to use try catch finally. here is my code, not the prettiest thing, but it works. The double filestream is used to clear the file.
Edit: sorry for posting that code snippet blush that was pretty bad 😛 I’ve posted my second try 🙂
internal static void SaveFileAsTxt()
{
FileStream streamer = new FileStream("Shipping2.txt", FileMode.Append, FileAccess.Write, FileShare.Write);
streamer.Close();
FileStream f = File.Open("Shipping2.txt", FileMode.Create);
f.Close();
StreamWriter writer = new StreamWriter("Shipping2.txt", true, Encoding.ASCII);
foreach (var shipment in _shipments)
{
string write = (shipment.Distance + ","+ shipment.Distance).ToString();
writer.WriteLine(write);
};
writer.Close();
}
//--------new code--------
internal static void SaveFileAsTxt()
{
if (File.Exists("Shipping2.txt"))
{
File.Delete("Shipping2.txt");
}
using (StreamWriter writer = new StreamWriter("Shipping2.txt", true, Encoding.ASCII))
{
foreach (var shipment in _shipments)
{
string write = (shipment.Duration + ","+ shipment.Distance).ToString();
writer.WriteLine(write);
}
}
}
You don’t need to open the file more than once – and you’re actually opening it three times at the moment. This should be fine;
File.CreateTextwill truncate the file if it already exists, and create it otherwise:Now, you say you want to use try/catch/finally – but why? If you fail to write to the file, do you definitely want to “handle” the exception in this method, rather than letting it bubble up to the caller?