Search code examples
c#streamwriter

StreamWriter to project directory and sub directory?


I'm currently having an issue with my application and I'm starting to think it's just my logic. I can't figure it out even after browsing these forms and MSDN.

I'm trying to use StreamWriter to create a text document in my app directory and create sub folder containing that document. Currently it just keeps dumping the file in my apps exe directory.

        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"))
        {

Solution

  • Try this:

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

    The reason I think is that your recipeDirectory and RecipeName + @".txt" aren't separated by the backslash, so the file is written to the parent directory instead and named recipeDirectory + RecipeName + @".txt".

    As an aside, I would also recommend you pass your RecipeName through a sanitizer function like this in case any name contains characters that can't be used in a file name:

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