【发布时间】:2014-07-07 20:04:50
【问题描述】:
我正在开发一个程序,该程序将读取 .lsp 文件,阅读它,部分理解并评论它,然后将编辑后的版本写回带有 .txt 附件的同一目录。我遇到的问题是,当我尝试运行程序时,Visual Studio 会抛出“不支持给定路径”错误,这可能是由于我的一些疏忽。谁能发现我的代码中会导致文件路径无效的部分?
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = @"C:\Users\Administrator\Documents\All Code\clearspan-autocad-tools-development\Code\Lisp";
openFileDialog1.Filter = "LISP files (*.lsp)|*.lsp|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
string loc;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
string[] lines = File.ReadAllLines(openFileDialog1.FileName);
// saves the document with the same name of the LISP file, but with a .txt file extension
using (StreamWriter sr = new StreamWriter(openFileDialog1.InitialDirectory + "\\" + openFileDialog1.FileName.Substring(0, openFileDialog1.FileName.Length - 4) + ".txt"))
{
foreach (string line in lines)
{
sr.WriteLine(line);
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
编辑:文件路径变量是“C:\Users\Administrator\Documents\All Code\clearspan-autocad-tools-development\Code\Lisp\heel.lsp”
另外,错误发生在我尝试初始化 StreamWriter 并将文件路径调整为 .txt 文件的行。
【问题讨论】:
-
哪一行会报错?那行变量的运行时值是多少?
-
旁白:您可以通过使用
System.IO.Path提供的方法来避免所有讨厌的字符串操作。即Path.Combine()和Path.ChangeExtension()。
标签: c# visual-studio path