我试图在c#中写一个文本文件

本文关键字:一个 文件 文本 | 更新日期: 2023-09-27 18:18:21

我有这个代码,但似乎没有做任何事情,所以我有点卡住

const string sPath = "movieAdd.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
if (listBox1.SelectedItems.Count ==1)
{
     foreach (var item in listBox1.SelectedItems)
     {
          SaveFile.WriteLine(item);
     }
     SaveFile.Close();
}

我试图在c#中写一个文本文件

代码只在选中列表中的一个条目时才写入行。我不确定这是否是您想要的,考虑到您正试图为每个选定的项目写一行。您可能希望将代码重写为以下内容,这样可以选择多个行。此外,在以下代码中,无论如何都会关闭文件。

const string sPath = "movieAdd.txt";
if (listBox1.SelectedItems.Count >= 1)
{
    using (System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath))
    {
        foreach (var item in listBox1.SelectedItems)
        {
            SaveFile.WriteLine(item);
        }
    }
}

另一个问题可能是您在sPath变量中没有显式路径。这可能会导致问题,具体取决于当前工作目录,该目录可能与可执行文件所在的目录不同!显式地添加一个目录会更安全,像这样:

const string sPath = @"C:'temp'movieAdd.txt";
if (listBox1.SelectedItems.Count >= 1)
{
    using (System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath))
    {
        foreach (var item in listBox1.SelectedItems)
        {
            SaveFile.WriteLine(item);
        }
    }
}

它没有指向任何地方…尝试const string sPath = @"C:'movieAdd.txt";或者类似的东西

甚至更好,使用Path方法来创建它,或者像这样:

const string sPath = @"c:'movieAdd.txt";
    List<string> strings_to_write = new List<string>():
        if (listBox1.SelectedItems.Count ==1)
        {
            foreach (var item in listBox1.SelectedItems)
            {
                strings_to_write.Add(item);
            }

    System.IO.File.WriteAllLines(sPath, strings_to_write);