C# 将列表框的项目保存到文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2293298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:10:01  来源:igfitidea点击:

Saving the items of a listbox to a text file

c#listboxtext-files

提问by roller

How can I save the contents of my listboxitems to a text file using a SaveFileDialog?

如何listbox使用SaveFileDialog? 将项目的内容保存到文本文件中?

I also want to add additional information to the text file and also add a MessageBoxsaying saved when it's been successful.

我还想在文本文件中添加其他信息,并添加MessageBox成功时保存的说法。

回答by Asad

To Save

保存

   // fetch the selected Text from your list
   string textToRight = listBox1.SelectedItem.ToString();  

   // Write to a file       
   StreamWriter sr = File.CreateText(@"testfile.txt");       
   sr.Write(textToRight);
   sr.Close();

Message

信息

   // display Message
   MessageBox.Show( "Information Saved Successfully" ); 

回答by Tanzelax

A SaveFileDialogis used with ShowDialog()to show it to the user, and if it's successful, using its OpenFile()to get the (File)Streamthat you write to. There's an example on the msdn page.

ASaveFileDialog用于将ShowDialog()其显示给用户,如果成功,则使用它OpenFile()来获取Stream您写入的(文件)。msdn 页面上有一个示例。

A ListBoxcan be accessed through its Itemsproperty, which is simply a collection of the items on it.

AListBox可以通过它的Items属性访问,它只是它上面的项目的集合。

回答by Paul Kohler

You have a few things going on there - make sure you split them up, e.g.

你有一些事情在那里 - 确保你把它们分开,例如

  • Get list box contents
  • Append Info
  • Write File
  • 获取列表框内容
  • 附加信息
  • 写文件

Please note!!There is a myriad of exceptions you can get while saving a file, see the docs and handle them somehow...

请注意!!在保存文件、查看文档并以某种方式处理它们时,您可以获得无数异常...

// Get list box contents
var sb = new StringBuilder();
foreach (var item in lstBox.Items)
{
    // i am using the .ToString here, you may do more
    sb.AppendLine(item);
}
string data = sb.ToString();

// Append Info
data = data + ????....

// Write File
void Save(string data)
{
    using(SaveFileDialog saveFileDialog = new SaveFileDialog())
    {
        // optional
        saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);

        //saveFileDialog.Filter = ???;

        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            File.WriteAllText(saveFileDialog.Filename);
            MessageBox.Show("ok", "all good etc");
        }
        else
        {
        // not good......
        }
    }
}

回答by nbushnell

this should do it.

这应该这样做。

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog f = new OpenFileDialog();

    f.ShowDialog();                 

    ListBox l = new ListBox();
    l.Items.Add("one");
    l.Items.Add("two");
    l.Items.Add("three");
    l.Items.Add("four");

    string textout = "";

    // assume the li is a string - will fail if not
    foreach (string li in l.Items)
    {
        textout = textout + li + Environment.NewLine;
    }

    textout = "extra stuff at the top" + Environment.NewLine + textout + "extra stuff at the bottom";
    File.WriteAllText(f.FileName, textout);

    MessageBox.Show("all saved!");
}

回答by spajce

        var saveFile = new SaveFileDialog();
        saveFile.Filter = "Text (*.txt)|*.txt";
        if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            using (var sw = new StreamWriter(saveFile.FileName, false))
                foreach (var item in listBox1.Items)
                    sw.Write(item.ToString() + Environment.NewLine);
            MessageBox.Show("Success");
        }

Also take note the StreamWriterhas a Type of Encoding.

还要注意StreamWriter有一个 Type of Encoding