我正在开发一个程序,该程序将读取 .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 文件的行。
openFileDialog.FileName
已经包含路径,因此将它与 openFileDialog.InitialDirectory
结合使用,使其成为类似于 C:\...\C:\...
这是无效的。
所以,只需使用
var txtFile= Path.ChangeExtension(openFileDialog1.FileName, ".txt");
我是一名优秀的程序员,十分优秀!