StreamWriter 到项目目录和子目录?

StreamWriter to project directory and sub directory?

我目前的申请有问题,我开始认为这只是我的逻辑。即使浏览了这些表格和 MSDN,我也无法弄清楚。

我正在尝试使用 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"))
        {

试试这个:

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());
}