在 C# 中将文件夹设置为用户指定的路径

本文关键字:用户 路径 设置 文件夹 | 更新日期: 2023-09-27 18:37:25

我正在尝试将控制台应用程序的当前文件夹设置为C#中用户指定的路径,但不能。我是编程新手,C#是我的第一门语言。这是到目前为止的代码,我不知道我哪里出了问题,我已经在互联网上搜索了这个,按照步骤操作,但它没有将文件夹设置为用户指定的文件夹。我在这里尝试做的是将文件夹路径更改为用户想要的路径,并将其设置为当前文件夹,然后用户可以从中访问其文件。

   DirectoryInfo folderInfo = new DirectoryInfo("C:''Windows");
   FileInfo[] files = folderInfo.GetFiles();
   Console.WriteLine("Enter Folder Name");
   string userInput = Console.ReadLine();
   FileInfo[] fileType = folderInfo.GetFiles(userInput + "*" + ".", SearchOption.TopDirectoryOnly); //searches for the folder the user has specified 
   Directory.SetCurrentDirectory(userInput);
   Console.WriteLine("{0}", userInput );
   Console.ReadLine();

我得到的错误是

"An unhandled exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll"
Additional information: Could not find a part of the path 'folder name here'.

请记住,我是这方面的初学者。提前谢谢你

在 C# 中将文件夹设置为用户指定的路径

调用 DirectoryInfo.GetFiles 时,第一个参数是文件模式(like *.* or *.txt),但您也可以指定引用文件夹的子文件夹。但是,您需要遵守指定文件夹的语法规则。创建文件夹名称的最佳方法是通过路径类的各种静态方法

DirectoryInfo folderInfo = new DirectoryInfo("C:''Windows");
Console.WriteLine("Enter Folder Name");
string userInput = Console.ReadLine();
string subFolder = Path.Combine(folderInfo.FullName, userInput);
// Check to verify if the user input is valid
if(Directory.Exists(subFolder))
{
    FileInfo[] fileType = folderInfo.GetFiles(Path.Combine(userInput, "*.*"), 
                                     SearchOption.TopDirectoryOnly);
    Directory.SetCurrentDirectory(subFolder);
    Console.WriteLine("{0}", Directory.GetCurrentDirectory());
}
else 
    Console.WriteLine("{0} doesn't exist", subFolder);

作为 DirectoryInfo 路径问题的一部分,您还应该考虑 SetCurrentDirectory 可以使用相对路径,但它被认为是相对于 CurrentDirectory 而不是初始 C:''WINDOWS(除非 C:''WINDOWS 是当前工作目录),所以如果你可以提供 SetCurrentDirectory 的完整路径,你会更安全。

您绝对需要完整路径才能使"目录"工作。

换句话说,它

永远不会找到"用户"或"Windows",它必须是"C:''Windows"。相对路径将起作用,但它相对于当前工作目录(应用程序目录)。

如果希望它有效,则需要运行:

Directory.SetCurrentDirectory("C:''");

运行文件搜索之前,相对路径将正确计算。此外,您的搜索模式搞砸了,正如@Steve提到的,您没有包含用户输入。