Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将列表框中的所有内容保存到.txt文件_C# - Fatal编程技术网

C# 将列表框中的所有内容保存到.txt文件

C# 将列表框中的所有内容保存到.txt文件,c#,C#,我正在尝试将列表框中的所有内容保存到.txt文件中。我有以下代码: private void btn_Save_Click(object sender, EventArgs e) { const string sPath = "save.txt"; System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath); SaveFile.WriteLine(listBox1.It

我正在尝试将列表框中的所有内容保存到.txt文件中。我有以下代码:

private void btn_Save_Click(object sender, EventArgs e)
{
     const string sPath = "save.txt";

     System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
     SaveFile.WriteLine(listBox1.Items);
     SaveFile.ToString();
     SaveFile.Close();

     MessageBox.Show("Programs saved!");
}
但是当我测试它时,代码可以工作,但它的行为就像它保存了文件一样,但是当我进入我的文件资源管理器时,我在任何地方都看不到文件


是否有人有任何答案

您需要提供明确的路径。例如:

const string sPath=@“C:\MyFolder\save.txt”

你必须做什么

第一:

你需要一个StreamWriter,你做得对。这个StreamWriter需要一条路径,你也这样做了

第二:

您需要列表框中的所有项目,因此请使用foreach。你没有这样做

第三:关闭小溪,你也这样做了。使用using而不是close,它更好:)执行相同的操作:)

我在哪里找到文件?在VisualStudio中右键单击项目->在windows资源管理器中打开->bin->调试,您的文本文件就是他们的。如果不提供绝对路径,则保存的数据始终位于.exe旁边

解决方案:

  string path = "save.txt";
        using (StreamWriter sw = new StreamWriter(path))
        {
            foreach (string s in listBox1.Items)
            {
                sw.WriteLine(s);
            }
        };

指定sPath的绝对路径
,则更容易找到“save.txt”file.BTW,如果找到“save.txt”,则内容将为“System.Windows.Forms.ListBox+ObjectCollection”。所以你的代码不是太好了点!或者可以执行
const string sPath=“C:\\MyFolder\\save.txt”