2015-01-13 32 views
1

我想將我的控制檯應用程序的當前文件夾設置爲用戶在C#中指定的路徑,但我不能。我是編程新手,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'. 

請記住我在這個初學者。 預先感謝您

+1

「不起作用」不是問題陳述。指定您想要的行爲以及您實際獲得的行爲,並告訴我們您收到的錯誤消息(如果有)。 –

+0

完成,多數民衆贊成我得到的錯誤消息 –

+0

你可以提供一些你輸入的示例輸入?例如:無論真正進入''文件夾名稱'這裏' –

回答

1

當您調用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的完整路徑,則更安全。

0

你絕對需要「目錄」工作的完整路徑。

換句話說,它會永遠發現 「用戶」 或 「窗口」,它是 「C:\ WINDOWS」。相對路徑將起作用,但相對於您當前的工作目錄(應用程序目錄)。

如果用戶希望工作,你需要運行:

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

以前運行你的文件搜索,所以相對路徑將正確評估。另外,您的搜索模式已經搞亂了,您不包括用戶輸入的內容,就像@Steve提到的那樣。

相關問題