Reputation: 39
I am trying to Edit a text file which is consist in resources folder of window form project. C#.
I am using this code but it is not writing over text file. No errors come from this
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Namespace.Properties.Resources.textfile))
{
for (int i = 0; i < res2.Count(); i++)
{
label3.Text = "Updating ... ";
label3.Visible = true;
label3.Refresh();
file.WriteLine("asdasD");
}
file.Close();
}
Upvotes: 2
Views: 2954
Reputation: 1582
I am able to write and then read a file using your code in a console application. Can you run this code (console application) and tell me if you have any exception ?
static void Main(string[] args)
{
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "textfile.txt");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName))
{
//if the file doesn't exist, create it
if (!File.Exists(fileName))
File.Create(fileName);
for (int i = 0; i < 2; i++)
{
file.WriteLine("asdas2");
}
}
using(System.IO.StreamReader fr = new StreamReader(fileName))
{
Console.WriteLine(fr.ReadToEnd());
}
}
Note, if you are trying to append to the existing file (write at the end of it and keep existing content), you need to use System.IO.StreamWriter(fileName, true).
Upvotes: 1
Reputation: 1720
As @LarsTech states in this answer, what you are trying to do is not recommended. Resource files are not meant to be written to--they should only be read from. If you want a place to put files, put them somewhere like Environment.SpecialFolders
.
You could also use the AppData
folder on the user's computer, which is typically used for exactly what you are trying to achieve:
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "textfile.txt");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName))
{
//if the file doesn't exist, create it
if (!File.Exists(fileName))
File.Create(fileName);
for (int i = 0; i < res2.Count(); i++)
{
label3.Text = "Updating ... ";
label3.Visible = true;
label3.Refresh();
file.WriteLine("asdasD");
}
}
As you can see, I removed the file.Close()
since it isn't necessary if you are using the using
block. You can do this if you are using a member which implements the IDisposable interface, which StreamWriter
does.
This should take care of everything for you. You won't have to create any files or worry about where they are.
Upvotes: 3