我试图在c#中写入文本文件

时间:2014-08-18 09:38:49

标签: c# visual-studio

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

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

2 个答案:

答案 0 :(得分:0)

它没有指向任何地方...... 试试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);

答案 1 :(得分:0)

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

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);
        }
    }
}