C# 我想用c写一个文本文件#
我有这个代码,但似乎没有做任何事情,所以我有点卡住了C# 我想用c写一个文本文件#,c#,visual-studio,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.W
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();
}
它没有指向任何地方。。。 尝试
conststringspath=@“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);
conststringspath=@“c:\movieAdd.txt”;
列表字符串\u to\u write=新列表():
if(listBox1.SelectedItems.Count==1)
{
foreach(列表框1.SelectedItems中的变量项)
{
字符串写入。添加(项);
}
System.IO.File.writeAllines(sPath、字符串到写入);
当前的代码仅在列表中选择了一个条目时才写入行。考虑到您试图为每个选定的条目写入一行,我不确定这是否是您想要的。您可能希望将代码重写为以下代码,这样可以选择多行。此外,在任何情况下,该文件都会在fol中关闭低编码
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);
}
}
}
现在发生了什么?有错误吗?他说。它什么也没做。thanx之前它什么都没做,现在它有了。谢谢你,我已经看到了错误是什么。