foreach 中的 Filestream 文件和 Streamwriter 并在完成后添加行

发布于 2025-01-10 21:52:38 字数 1919 浏览 4 评论 0原文

就像现在我正在尝试使用 FileStream 打开我的文件一样,与每次通过 Streamwriter 将其写入文件相比,我对使用 Streamwriter 的代码有了更深入的了解。

当它第一次跑完时,就没有任何问题,但当我跑完第二圈时。然后它会失败,然后写入“Stream 不可写

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

我想通过此实现的是每次通过 StreamWriter 运行时都必须将文本插入到文件中。当它完成时,它不应该首先到达最后。

我已阅读:

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

C# 如何更新文件(保留旧文件)数据)

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(
quot;{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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冰之心 2025-01-17 21:52:39

假设您至少使用 .NET Framework 4.5。

StreamWriter 在其 Dispose() 方法中关闭基本流。您可以使用另一个构造函数来调整该行为: https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter.-ctor?view=netcore-3.1#system-io-streamwriter-ctor(system-io-stream-系统文本编码系统int32系统布尔值)

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://learn.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)

怪我鬧 2025-01-17 21:52:38

目前,您正在创建一个 StreamWriter,对其进行写入,并为每个列表处理它,这就是导致问题的原因。在内部,Dispose 方法关闭导致异常的底层流。为了解决这个问题,我们可以执行以下两件事之一:

  1. 告诉我们的 StreamWriter 不要关闭底层流。
  2. 在我们也处理完底层流之前,不要处置我们的 StreamWriter

以下是如何执行#1:

只需用此替换对构造函数的调用

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

以下是如何执行#2:

using (StreamWriter ... 块向上移动到比 深一层” code>using (FileStream ... block 就

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

我个人而言,我会选择#2,因为我不喜欢在循环中创建和处置对象

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文