Visual Studio:给定路径不支持错误

时间:2014-05-19 18:40:27

标签: c# visual-studio path

我正在开发一个程序,它将读取.lsp文件,读取它,部分理解并对其进行注释,然后将编辑后的版本写回带有.txt附件的同一目录。我遇到的问题是,当我尝试运行程序时,visual studio会抛出“Given path not supported”错误,这可能是由于我的疏忽造成的。任何人都可以发现我的代码的一部分会导致文件路径无效吗?

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文件的行上发生错误。

3 个答案:

答案 0 :(得分:4)

openFileDialog.FileName已包含路径,因此将其与openFileDialog.InitialDirectory相结合会使其成为C:\...\C:\...之类的无效路径。

所以,只需使用

var txtFile= Path.ChangeExtension(openFileDialog1.FileName, ".txt");

答案 1 :(得分:0)

您的代码有几个问题。

错误处理: 由于您的错误处理,您显然不知道错误发生在哪一行。如果没有它进行调试可能会很有用。

<强>循环: 您将整个输入文件拉入内存,然后循环遍历每一行以进行写入。如果要处理的文件足够小,那就行了,但我会将foreach循环移到读取文件的块之外。

字符串解析: 我建议将路径和文件名存储在变量中,而不是仅仅引用控件。这将使其更具可读性。此外,System.IO.Path.Combine()可以帮助构建路径,而不必担心字符串连接。

<强>总体: 您可能希望将此重构为一个方法,其签名如下:

void ProcessLispFile(string inputFile, string outputFile) { }

答案 2 :(得分:0)

openFileDialog.FileName返回文件的完整路径,而不仅仅是函数所暗示的名称。

因此尝试将其与openFileDialog.InitialDirectory结合使用会产生与您期望的不同的字符串

您可以使用更改扩展方法将其更改为输出的文件类型

  

var txtFile = Path.ChangeExtension(openFileDialog1.FileName,“。txt”);

相关问题