patterncsharpMinor
More idiomatic way to handle simple file writing in C#?
Viewed 0 times
simplefilehandlemoreidiomaticwaywriting
Problem
Is there anything you would change about the following function? I welcome any feedback on style, correctness, etc. Thank you for reading.
Some of my questions are:
-
Is there another, "better-in-general" way of writing to files?
Some of my questions are:
- Obviously, I catch the exception and convert it to a return value because I don't want to take down the application in case of an error. Would it be better to allow the exception to propagate up and handle it there (in the function that is coordinating the creation of the set of import files)?
-
Is there another, "better-in-general" way of writing to files?
private static bool CreateImportFile(string path, string content)
{
try
{
using (var fileStreamWriter = File.CreateText(path))
{
fileStreamWriter.Write(content);
fileStreamWriter.Close();
}
}
catch (IOException e)
{
Console.WriteLine("Failed to write import file due to IOException. " + e.Message);
return false;
}
return true;
}Solution
I think this is more idiomatic but I think this style does not really add much benefit over calling
File.WriteAllText directly. Consider what your client code will need to do to handle a single bool result with no other information as to why it failed.private static bool CreateImportFile(string path, string content)
{
try
{
File.WriteAllText(path, content);
}
catch (IOException e)
{
Console.WriteLine("Failed to write import file due to IOException. " + e.Message);
return false;
}
return true;
}Code Snippets
private static bool CreateImportFile(string path, string content)
{
try
{
File.WriteAllText(path, content);
}
catch (IOException e)
{
Console.WriteLine("Failed to write import file due to IOException. " + e.Message);
return false;
}
return true;
}Context
StackExchange Code Review Q#5361, answer score: 3
Revisions (0)
No revisions yet.