【问题标题】:Visual Studio: Given Path Not Supported ErrorVisual Studio:给定路径不支持错误
【发布时间】: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


【解决方案1】:

openFileDialog.FileName 已包含路径,因此将其与 openFileDialog.InitialDirectory 组合使其成为无效的路径,如 C:\...\C:\...

所以,请使用

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

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      【解决方案3】:

      您的代码有几个问题。

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

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

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

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

      void ProcessLispFile(string inputFile, string outputFile) { }
      

      【讨论】:

      • 没错,但不是答案。
      • Thomas,这可能不是答案,但按照我的建议会指出问题所在。
      猜你喜欢
      • 2018-09-06
      • 2017-06-26
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 2019-01-16
      • 2014-11-19
      • 2012-03-08
      相关资源
      最近更新 更多