Home > Back-end >  Filestream file and Streamwriter in foreach and add line when done
Filestream file and Streamwriter in foreach and add line when done

Time:03-01

It's like that that right now I'm trying to open my file with FileStream where I saw a little further into the code to use streamwriter compared to writing it into the file every time it goes through Streamwriter.

When it runs through the first time then do it without any problems but as soon as I run it through the second lap. then it fails where it then writes "Stream was not writable"

int count = 0;
using (FileStream fs = new FileStream(@"C:\jpe\Projekt\Utilities\Icons\Icons/WriteLines.txt", FileMode.Append, FileAccess.Write))
{
    foreach (SPSite tmpSite in tmpRootColl)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(string.Format("Title {0}", tmpSite.RootWeb.Title));
        //Enumerate through each sub-site
        foreach (SPWeb tmpWeb in tmpSite.AllWebs)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine(string.Format("Title {0}", tmpWeb.Title));
            //Enumerate through each List
            foreach (SPList tmpList in tmpWeb.Lists)
            {
                if (tmpList.BaseTemplate == SPListTemplateType.DocumentLibrary)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine(string.Format("Title {0}", tmpList.Title));
                    using (StreamWriter outputFile = new StreamWriter(fs)) //Errors come here when it runs the second round through.
                    {
                        await outputFile.WriteLineAsync($"{tmpSite.RootWeb.Title} - {tmpList.Title} {count}");
                    }
                    count  ;
                }
            }
        }
        Console.WriteLine("__________________________________________________");
    }
}

What I want to achieve with this is that it has to insert text into the file every time it runs through StreamWriter. It should not first make it to the last when it is finished.

i have read:

https://stackoverflow.com/a/7306243/18055701

C# how to update file(leave old data)

CodePudding user response:

Currently you're creating a StreamWriter, writing to it, and disposing it for every list, this is what's causing the issue. Internally the Dispose method closes the underlying stream causing the exception. To solve this we can do one of 2 things

  1. Tell our StreamWriter to not close the underlying stream.
  2. Not dispose our StreamWriter until we're also done with the underlying stream.

Here's how to do #1:

Simply replace your call to the constructor with this

using (StreamWriter outputFile = new StreamWriter(fs, leaveOpen: true))

Here's how to do #2:

Move the using (StreamWriter ... block up to be "one level deeper" than the using (FileStream ... block

using (FileStream fs = new FileStream("..."))
{
    using (StreamWriter outputFile = new StreamWriter(fs))
    {
        // Your foreach loops here
    }
}

Personally I'd go with #2 as I'm not a fan of creating and disposing objects in a loop

CodePudding user response:

Assuming you are using at least .NET framework 4.5.

The StreamWriter closes the base stream in its Dispose() method. You can adjust that behavior by using another construcor: https://docs.microsoft.com/en-us/dotnet/api/system.io.streamwriter.-ctor?view=netcore-3.1#system-io-streamwriter-ctor(system-io-stream-system-text-encoding-system-int32-system-boolean)

  • Related