2016-04-08 30 views
1

我目前对我的应用程序有问题,我开始认为这只是我的逻辑。即使在浏览这些表单和MSDN后,我也无法弄清楚。StreamWriter到项目目录和子目录?

我正在尝试使用StreamWriter在我的应用程序目录中创建文本文档并创建包含该文档的子文件夹。目前它只是将文件保存在我的应用程序的exe目录中。

 string runTimeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); 

     string recipeDirectory = Path.Combine(runTimeDirectory, "Recipes"); 
     if (!Directory.Exists(recipeDirectory)) 
     { 
      //Recipes directory doesnt exist so create it 
      Directory.CreateDirectory(recipeDirectory); 
     } 

     // Write text to file 
     using (StreamWriter OutputFile = new StreamWriter(recipeDirectory + RecipeName + @".txt")) 
     { 
+0

只是一个猜测,但'recipeDirectory'可能不会以'\'结尾,所以你最终得到:'C:\ foo \ Recpiesmyrecipe.txt'而不是:'C:\ foo \ Recipies \ myrecipie.txt“ – CodingGorilla

+0

这是正确的,它创建文件+文件目录名我在下面的答案中看到我的问题 –

回答

3

试试这个:

using (StreamWriter OutputFile = new StreamWriter(
    Path.Combine(recipeDirectory, RecipeName + @".txt"))) 

我想原因是你recipeDirectoryRecipeName + @".txt"没有被反斜杠隔开的,因此文件写入到父目录,而不是和命名recipeDirectory + RecipeName + @".txt"

顺便说一句,我也建议你通过RecipeName通过这样的消毒功能的情况下,任何名称中包含不能在文件名中使用的字符:

internal static string GetSafeFileName(string fromString) 
{ 
    var invalidChars = Path.GetInvalidFileNameChars(); 
    const char ReplacementChar = '_'; 

    return new string(fromString.Select((inputChar) => 
     invalidChars.Any((invalidChar) => 
     (inputChar == invalidChar)) ? ReplacementChar : inputChar).ToArray()); 
} 
+0

我以为相同,但你会认为这将是显而易见的,因为所创建的文件将具有晦涩的名字 – CodingGorilla

+1

明显是相对的... –

+0

不是'Path.Combine'为你做的吗? –