【问题标题】:Won't look for files in the correct location, instead it looks in the \source\repos\<project> folder不会在正确的位置查找文件,而是在 \source\repos\<project> 文件夹中查找
【发布时间】:2018-04-28 20:38:20
【问题描述】:

我正在 VS2017 中创建一个 C# 程序,它将读取位于 C:\Program Files 文件夹的子文件夹中的文件。当我尝试启动应用程序时,我收到一条错误消息,提示它无法在 C:\Users\&lt;loginname&gt;\source\repos\&lt;solutionname&gt;\bin\debug\\&lt;folder name that contains the file&gt; 中找到文件。在代码中,它停在foreach (string line in File.ReadLines(file) 处,说它找不到文件并显示错误消息

System.IO.FileNotFoundException: '找不到文件'C:\Users\Username>\source\repos\NewApp\NewApp\bin\Debug\SubDirectory'。"

应该是从"C:\Program Files\MyApp\SubDirectory\"读取文件 在 Visual Studio 的早期版本中,这按预期工作,但这只发生在 VS 2017 中。
我的代码如下:

string[] FileDirs = Directory.GetDirectories(Path.Combine(@"C:\Program Files\"+"\MyApp\"));
foreach (string dir in SubDirs)
{
    string file = Path.GetFileName(dir);
    foreach (string line in File.ReadLines(file))
    {
        if (line.StartsWith("StartText"))
        {
            string TextToAdd = line;

            ListBox.Items.Add(TextToAdd);
        }
    }
}

我还尝试用 Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) 替换硬编码的程序文件目录,但它却说找不到 Program Files (X86) 目录下的文件夹:

"System.IO.DirectoryNotFoundException: '找不到一部分 路径'C:\Program Files (x86)\MyApp\"

它应该在 C:\Program Files 文件夹中查找,而不是 C:\Program Files (x86) 文件夹。 (顺便说一句,它是 Win 10 64 位操作系统)

【问题讨论】:

  • 您的字符串连接语法已关闭:MyApp 是变量吗?
  • Program FilesSpecialFolderPath.Combine 不是那样使用的。
  • 是的,如果要引用程序文件,可以使用%programfiles%。系统上可能不存在文字 programfiles
  • 无论哪种方式,它都做同样的事情。我正在快速输入此帖子的代码。它应该是 "C:\Program Files\" 此外,如果我将它更改为不同的路径,例如 "D:\TestFolder\",它仍然会执行相同的操作。 “MyApp”是实际的文件夹名称。

标签: c#


【解决方案1】:

Program Files 是一个SpecialFolder。您必须使用以下方式引用它:

Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)

实际返回的路径可能是“C:\Program Files”或“C:\Program Files (x86)”,具体取决于当前项目配置。
如果定位x86 或启用Prefer 32-bit,则返回的路径为“C:\Program Files (x86)”。

Path.Combine() 以字符串形式链接路径段,您可以提供以逗号分隔或作为字符串数组的形式:

Path.Combine("[Part1]", "[Part2]")

结果是这样的:

string MyPath = "[SomeDirectoryName-Possibly-Without-Leading-BackSlash]";
string[] FileDirs = Directory.GetDirectories(
                    Path.Combine(
                        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), 
                        MyPath));

【讨论】:

  • 我就是这样做的:string[] FileDirs = Directory.GetDirectories(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)"+"\MyApp\"));
  • @Tornado726 不。再看一遍。那个 "+"\MyApp\" 不正确。您必须用 逗号 分隔各个段。
  • 添加逗号而不是加号会使 VS 认为它是 UNC 路径。编辑:使 VS 链接成为 UNC 路径是另一个问题。
  • @Tornado726 不,它没有。你有运行我发布的代码吗?尝试将“C:\Program Files”或“C:\Program Files (x86)”中的现有目录用作MyPath(取决于您的活动配置)。您会看到它返回了该路径中的所有子目录。
  • Jimi,您的代码确实解决了原始问题,但现在的问题是我需要它查看 C:\Program Files\MyApp 文件夹,而不是 C:\Program Files (x86 )\MyApp 文件夹。
猜你喜欢
  • 2015-05-30
  • 1970-01-01
  • 2011-01-23
  • 2020-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多