问题描述
我的程序包含一种形式和七个用户控件.我正在使用MS Visual Studio 2010 C#语言.
My program contains one form and seven user controls. I am using MS Visual Studio 2010 C# Language.
我的程序::将.txt文件中的所有文本显示到UserControl的文本框中.
My Program: Displays all the text in the .txt file into a textbox in UserControl.
我的目标:我要检查.txt文件是否存在.如果.txt文件不存在,请创建它,以便用户可以将一些数据放入.txt文件中,然后将其显示在UserControl的文本框中.如果.txt文件已经存在,则直接将.txt文件中的数据显示在文本框中.
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.
我用于检查文件是否存在于FORM中的代码:
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);
}
}
用于将文本从.txt文件读取到UserControl中的TextBox的代码:(这与其余6个usercontrol及其文本框相同.仅.txt文件和文本框的名称相应不同.
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
那我该怎么办?
推荐答案
提到原因.您可以尝试以下操作:-
The reason is mentioned here. You can try this:-
if(!File.Exists(FilePath)){
File.Create(FilePath).Close();}
File.WriteAllText(FileText);
这篇关于无法访问刚刚创建的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!