My program contains one form and seven user controls. I am using MS Visual Studio 2010 C# Language.
My Program: Displays all the text in the .txt file into a textbox in UserControl.
My Aim: I want to check if .txt file exists. If .txt file does not exist, create it so that the user can put some data in .txt file which is then displayed in the text boxes in UserControl. If .txt file already exists, directly display data from .txt file into text box.
My code for checking if the file exists or not in FORM:
private void Form1_Load(object sender, EventArgs e)
{
string path1 = @"C:\Users\PK\Documents\Visual Studio 2010\ABC.txt";
if (!File.Exists(path1))
{
File.Create(path1);
}
string path2 = @"C:\Users\PK\Documents\Visual Studio 2010\DEF.txt";
if (!File.Exists(path2))
{
File.Create(path2);
}
string path3 = @"C:\Users\PK\Documents\Visual Studio 2010\GHI.txt";
if (!File.Exists(path3))
{
File.Create(path3);
}
string path4 = @"C:\Users\PK\Documents\Visual Studio 2010\JLK.txt";
if (!File.Exists(path4))
{
File.Create(path4);
}
string path5 = @"C:\Users\PK\Documents\Visual Studio 2010\MNO.txt";
if (!File.Exists(path5))
{
File.Create(path5);
}
}
Code to read text from .txt file to TextBox in UserControl: (This is same for the remaining 6 usercontrol and it's textboxes. Only names of .txt files and textboxes differ accordingly.
private void UserControl1_Load(object sender, EventArgs e)
{
textBox5.Text = File.ReadAllText(@"C:\Users\PK\Documents\Visual Studio 2010\ABC.txt");
}
So, When I RUN the program, I get the following error:
IOException was unhandled
The process cannot access the file 'C:\Users\PK\Documents\Visual Studio 2010\ABC.txt' because it is being used by another process.
So, what should I do?