我正在尝试使用try catch来检查filelocation中的文件是否存在。 如果它不是我想要打开文件对话框并允许用户能够选择文本文件(并且只有文本文件)并读取所选文件的文件位置并将其用作sream reader的文件位置< / p>
任何时候我使用它,文件位置将一直到最后。而不是文件名,它将有bin / debug / ok
try
{
if (!File.Exists(filelocation))
{
throw new FileNotFoundException();
}
else
{
StreamReader question = new StreamReader(filelocation);
}
}
catch (System.IO.FileNotFoundException)
{
MessageBox.Show("File containing the questions not found");
OpenFileDialog OFD = new OpenFileDialog();
DialogResult result = OFD.ShowDialog();
string filelocation = result.ToString();
StreamReader question = new StreamReader(filelocation);
}
答案 0 :(得分:3)
添加此
OFD .Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
结果将是:
try
{
if (!File.Exists(filelocation))
{
throw new FileNotFoundException();
}
else
{
StreamReader question = new StreamReader(filelocation);
}
}
catch (System.IO.FileNotFoundException)
{
MessageBox.Show("File containing the questions not found");
OpenFileDialog OFD = new OpenFileDialog();
OFD .Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
DialogResult result = OFD.ShowDialog();
string filelocation = result.ToString();
StreamReader question = new StreamReader(filelocation);
}
答案 1 :(得分:1)
这考虑了用户是否未从文件对话框中选择文件或是否选择了无效文件...
StreamReader ReadME;
if (!File.Exists(termfilelocation))
{
MessageBox.Show("File containing the questions not found");
OpenFileDialog OFD = new OpenFileDialog();
OFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
// this will filter out any file that isnt a text file
ofd.CheckFileExists = true;//this will not allow invalid files.
DialogResult dr = OFD.ShowDialog();
if (dr == DialogResult.Cancel)
{
//User did not select a file.
return;
}
String result = OFD.FileName;
ReadME = new StreamReader(result);
termfilelocation = result;
}
else
{
ReadME = new StreamReader(termfilelocation);
}
答案 2 :(得分:-2)
我自己修好了,所以在这里遇到类似问题的任何人都有如何解决它
try
{
if (!File.Exists(termfilelocation))
{
throw new FileNotFoundException();
}
else
{
StreamReader reader = new StreamReader(termfilelocation);
}
}
catch (System.IO.FileNotFoundException)
{
MessageBox.Show("File containing the questions not found");
// this will display a message box sying whats in ("")
OpenFileDialog OFD = new OpenFileDialog();
// this will create a new open file dialog box
OFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
// this will filter out any file that isnt a text file
DialogResult = OFD.ShowDialog();
String result = OFD.FileName;
// this will give the result to be the file name
// that was choosen in the open file dialog box
StreamReader reader = new StreamReader(result);
termfilelocation = result;
}