4

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?

Servy
  • 202,030
  • 26
  • 332
  • 449
Smith
  • 387
  • 3
  • 6
  • 14
  • @Smith:- Please check if your file is being used somewhere or is currently open or is being used by any other application!! – Rahul Tripathi Aug 22 '13 at 18:46
  • @DaveZych: Thanks for looking at my question. Yes, the error says the same. How should I get rid of this error and get my program working? – Smith Aug 22 '13 at 18:46
  • @RahulTripathi: No, all the files are closed. No other program is using it. – Smith Aug 22 '13 at 18:47

1 Answers1

10

The reason is mentioned here. You can try this:-

if(!File.Exists(FilePath)){
    File.Create(FilePath).Close();}
    File.WriteAllText(FileText);
Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331