我必须打开并从.txt文件中读取,这是我正在使用的代码:
Stream myStream;
openFileDialog1.FileName = string.Empty;
openFileDialog1.InitialDirectory = "F:\\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var compareType = StringComparison.InvariantCultureIgnoreCase;
var fileName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
var extension = Path.GetExtension(openFileDialog1.FileName);
if (extension.Equals(".txt", compareType))
{
try
{
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetFullPath(file); //when i did it like this it's work fine but all the time give me same path whatever where my "*.txt" file is
//Insert code to read the stream here.
//fileName = openFileDialog1.FileName;
StreamReader reader = new StreamReader(path);
MessageBox.Show(file, "fileName");
MessageBox.Show(path, "Directory");
}
}
// Exception thrown: Empty path name is not legal
catch (ArgumentException ex)
{
MessageBox.Show("Error: Could not read file from disk. " +
"Original error: " + ex.Message);
}
}
else
{
MessageBox.Show("Invaild File Type Selected");
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码抛出一个异常,说"空路径名不合法".
我究竟做错了什么?
正如hmemcpy所指出的,您的问题在于以下几行
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetDirectoryName(file);
StreamReader reader = new StreamReader(path);
MessageBox.Show(file, "fileName");
MessageBox.Show(path, "Directory");
}
Run Code Online (Sandbox Code Playgroud)
我要打破你了:
/*
* Opend the file selected by the user (for instance, 'C:\user\someFile.txt'),
* creating a FileStream
*/
using (myStream = openFileDialog1.OpenFile())
{
/*
* Gets the name of the the selected by the user: 'someFile.txt'
*/
string file = Path.GetFileName(openFileDialog1.FileName);
/*
* Gets the path of the above file: ''
*
* That's because the above line gets the name of the file without any path.
* If there is no path, there is nothing for the line below to return
*/
string path = Path.GetDirectoryName(file);
/*
* Try to open a reader for the above bar: Exception!
*/
StreamReader reader = new StreamReader(path);
MessageBox.Show(file, "fileName");
MessageBox.Show(path, "Directory");
}
Run Code Online (Sandbox Code Playgroud)
你应该做的是将代码改为类似的东西
using (myStream = openFileDialog1.OpenFile())
{
// ...
var reader = new StreamReader(myStream);
// ...
}
Run Code Online (Sandbox Code Playgroud)
您希望用户只选择.txt文件吗?然后使用.Filter属性,如下所示:
openFileDialog1.Filter = "txt files (*.txt)|*.txt";
Run Code Online (Sandbox Code Playgroud)
你的错误在于:
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetDirectoryName(file);
Run Code Online (Sandbox Code Playgroud)
在第一行中,file变量将仅包含文件名,例如MyFile.txt,使第二行向path变量返回空字符串.在代码中,您将尝试StreamReader使用空路径创建一个,这就是抛出异常的原因.
顺便说一句,这正是异常告诉你的.如果删除try..catch使用块周围的内容,您会在Visual Studio中调试期间看到它.
| 归档时间: |
|
| 查看次数: |
17094 次 |
| 最近记录: |