Unable to access a file that was just created [duplicate]

馋奶兔 提交于 2019-12-14 01:19:31

问题


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?


回答1:


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

if(!File.Exists(FilePath)){
    File.Create(FilePath).Close();}
    File.WriteAllText(FileText);


来源:https://stackoverflow.com/questions/18388452/unable-to-access-a-file-that-was-just-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!