Reputation: 267
I have the following code:
private void Write(string path, string txt)
{
string dir =Path.GetDirectoryName(path);
try
{
if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); }
if (!File.Exists(path))
{
File.Create(path).Dispose();
using (TextWriter tw = new StreamWriter(path))
{
tw.WriteLine(txt);
tw.Close();
}
}
else
{
using (TextWriter tw = new StreamWriter(path, true))
{
tw.WriteLine(txt);
}
}
}
catch (Exception ex)
{
//Log error;
}
}
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\html\\Static_1.html"
is passed in the path parameter and some html text is passed for the txt parameter. Code fails at File.Create()
. I get the following error:
Could not find file 'C:\Users\Xami Yen\Documents\html\Static_1.html
What is wrong with this code? Can't figure it out.
Upvotes: 1
Views: 176
Reputation: 18169
Try this:
private void Write(string path, string txt, bool appendText=false)
{
try
{
string directory = Path.GetDirectoryName(path);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
if (appendText)
{
// Appends the specified string to the file, creating the file if it does not already exist.
File.AppendAllText(path, txt);
}
else
{
// Creates a new file, write the contents to the file, and then closes the file.
// If the target file already exists, it is overwritten.
File.WriteAllText(path, txt);
}
}
catch (Exception ex)
{
//Log error
Console.WriteLine($"Exception: {ex}");
}
}
Upvotes: 1
Reputation: 303
MSDN Documentation:
File.WriteAllText
method creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.
Also, please make sure you have Write permissions to the newly created folder.
private void Write(string path, string txt)
{
var dir = Path.GetDirectoryName(path);
try
{
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
File.WriteAllText(path, txt);
}
catch (Exception ex)
{
//Log error;
}
}
Upvotes: 1