在内存中写入文本文件并使用 savefiledialog 保存

发布于 2024-11-02 05:16:25 字数 570 浏览 0 评论 0原文

我正在尝试在内存中创建一个文本文件,向其中添加一些行,最后将文件保存在文本文件中。我可以处理保存的对话框部分,但我不知道如何从内存中获取文本文件。任何帮助和提示将不胜感激。

到目前为止我正在做的是:

//Initialize in memory text writer
MemoryStream ms = new MemoryStream(); 
TextWriter tw = new StreamWriter(ms);

tw.WriteLine("HELLO WORLD!");
tw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!);

请注意 我将调用 tw.WriteLine() 在不同的地方添加更多行,所以我想在程序结束时保存它(所以这应该包含在 using{} 之类的东西之间)

UPDATE

StringBuilder 似乎是一个这样做的更可靠的选择!当我使用 MemoryStream 执行此操作时,我的文本文件中出现了奇怪的剪切内容。

谢谢。

I am trying to make a text file in memory, add some lines to it and at the end save the file in a text file. I can handle the savedialog part but I dont know how to get the text file from memory. Any help and tips will be appriciated.

What I am doing so far is:

//Initialize in memory text writer
MemoryStream ms = new MemoryStream(); 
TextWriter tw = new StreamWriter(ms);

tw.WriteLine("HELLO WORLD!");
tw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!);

please note
I will call tw.WriteLine() add more lines in different places so I want to save this at end of program (so this shouldent be wrapped between something like using{} )

UPDATE

StringBuilder seems to be a more reliable option for doing this! I get strange cut-outs in my text file when I do it using MemoryStream.

Thanks.

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

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

发布评论

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

评论(5

堇色安年 2024-11-09 05:16:25

我认为这里最好的选择是写入 StringBuilder,完成后,File.WriteAllText。如果内容很大,您可能会首先考虑直接写入文件(通过File.CreateText(path)),但对于中小型文件这应该没问题。

var sb = new StringBuilder();

sb.AppendLine("HELLO WORLD!");
sb.AppendLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!");

File.WriteAllText(path, sb.ToString());

I think your best option here would be to write to a StringBuilder, and when done, File.WriteAllText. If the contents are large, you might consider writing directly to the file in the first place (via File.CreateText(path)), but for small-to-medium files this should be fine.

var sb = new StringBuilder();

sb.AppendLine("HELLO WORLD!");
sb.AppendLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!");

File.WriteAllText(path, sb.ToString());
傲娇萝莉攻 2024-11-09 05:16:25

或者,与@Marc的答案几乎相同,但足够不同,我认为值得将其作为有效的解决方案发布:

using (var writer = new StringWriter())
{
    writer.WriteLine("HELLO WORLD!");
    writer.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!");
    File.WriteAllLines(path, writer.GetStringBuilder().ToString());
}

其中 path 是一个表示有效文件系统条目路径的字符串,是预定义的由您在应用程序中的某个位置。

Or, something nigh-on the same as @Marc's answer, but different enough that I think it's worth putting out there as a valid solution:

using (var writer = new StringWriter())
{
    writer.WriteLine("HELLO WORLD!");
    writer.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!");
    File.WriteAllLines(path, writer.GetStringBuilder().ToString());
}

Where path is a string representing a valid file system entry path, predefined by you somewhere in the application.

坏尐絯 2024-11-09 05:16:25

假设您的 SaveFileDialog 名称是“dialog”,

File.WriteAllBytes(dialog.FileName, Encoding.UTF8.GetBytes("Your string"));

或者

var text = "Your string";
text += "some other text";
File.WriteAllText(dialog.FileName, text);

在您自己的解决方案中,您可以执行以下操作:

MemoryStream ms = new MemoryStream(); 
TextWriter tw = new StreamWriter(ms);

tw.WriteLine("HELLO WORLD!");
tw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!);

// just add this
File.WriteAllBytes(dialog.FileName, ms.GetBuffer());

Assume your SaveFileDialog name is "dialog"

File.WriteAllBytes(dialog.FileName, Encoding.UTF8.GetBytes("Your string"));

or

var text = "Your string";
text += "some other text";
File.WriteAllText(dialog.FileName, text);

also in your own solution you can do this :

MemoryStream ms = new MemoryStream(); 
TextWriter tw = new StreamWriter(ms);

tw.WriteLine("HELLO WORLD!");
tw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!);

// just add this
File.WriteAllBytes(dialog.FileName, ms.GetBuffer());
只为一人 2024-11-09 05:16:25

像这样的东西。

Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension

// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();

// Process save file dialog box results
if (result == true)
{
    // Save document
    using (FileStream file = File.CreateText(dlg.FileName)
    {
        ms.WriteTo(file)
    }
}

我并不担心该文件是否已经存在,但这应该会让您接近。

您可能还需要 ms.Seek(SeekOrgin.Begin, 0)

Something like this.

Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension

// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();

// Process save file dialog box results
if (result == true)
{
    // Save document
    using (FileStream file = File.CreateText(dlg.FileName)
    {
        ms.WriteTo(file)
    }
}

I haven't worried about whether the file already exists but this should get you close.

You might need a ms.Seek(SeekOrgin.Begin, 0) too.

美胚控场 2024-11-09 05:16:25

将文本附加到文件末尾的另一种方法可能是:

if (saveFileDialog.ShowDialog() == DialogResult.OK) {
    using (var writer = new StreamWriter(saveFileDialog.Filename, true)) {
        writer.WriteLine(text);
    }
}

假设 text 是您需要保存到文件中的字符串。
如果您想以简单的方式向该字符串追加新行,您可以这样做:

var sb = new StringBuilder();
sb.AppendLine("Line 1");
sb.AppendLine("Line 2");

并且结果字符串将为 sb.ToString()

如果您已经有一个 Stream对象(在您的示例中为 MemoryStream),您可以执行相同的操作,但将行:替换

using (var writer = new StreamWriter(saveFileDialog.Filename, true)) {

using (var writer = new StreamWriter(memoryStream)) {

Edit:
关于将语句包装在 using 中:

考虑一下这根本不是问题。在我的第一个示例中,您所要做的就是保留该 StringBuilder 对象,并不断向其添加行。一旦获得所需内容,只需将数据写入文本文件即可。

如果您打算多次写入文本文件,只需在每次写入时清除StringBuilder,以免获得重复的数据。

Another way of appending text to the end of a file could be:

if (saveFileDialog.ShowDialog() == DialogResult.OK) {
    using (var writer = new StreamWriter(saveFileDialog.Filename, true)) {
        writer.WriteLine(text);
    }
}

supposing that text is the string you need to save into your file.
If you want to append new lines to that string in an easy way, you can do:

var sb = new StringBuilder();
sb.AppendLine("Line 1");
sb.AppendLine("Line 2");

and the resulting string will be sb.ToString()

If you already have a Stream object (in your example, a MemoryStream), you can do the same but replace the line:

using (var writer = new StreamWriter(saveFileDialog.Filename, true)) {

by

using (var writer = new StreamWriter(memoryStream)) {

Edit:
About wrapping the statements inside using:

Take in count that this is not a problem at all. In my first example, all you will have to do is to keep that StringBuilder object, and keep adding lines to it. Once you have what you want, just write the data into a text file.

If you are planning to write more than once to the text file, just clear the StringBuilder everytime you write, in order to not get duplicated data.

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