将逗号分隔的字符串逐行写入文件
此 cide 旨在从富文本框(即用逗号分隔的用户列表)中获取文本,然后将每个条目写在自己的行上。
然而,事实并非如此。我做错了什么?
if (chkWhiteList.Checked)
{
string rawUser = rtboxWhiteList.Text;
string[] list = rawUser.Split(new char[] { ',' });
foreach (string user in list)
{
using (StreamWriter whiteList = new StreamWriter(cleanDir + @"\white-list.txt"))
{
whiteList.WriteLine(String.Format("{0}\r\n", user));
}
}
}
This cide is meant to take the text from a rich text box (that is a list of users separated by commas) and then write each entry on its own line.
However, it does not. What have I done wrong?
if (chkWhiteList.Checked)
{
string rawUser = rtboxWhiteList.Text;
string[] list = rawUser.Split(new char[] { ',' });
foreach (string user in list)
{
using (StreamWriter whiteList = new StreamWriter(cleanDir + @"\white-list.txt"))
{
whiteList.WriteLine(String.Format("{0}\r\n", user));
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我会交换你的
using
和for 循环
。并删除换行符I would swap your
using
andfor loop
around. And remove the new line characters你的 foreach 和你的 using 是错误的。您需要使用来设置流写入器,然后在其中执行循环(foreach)来写入行。
(这是对你的代码的粗略修改。)
Your foreach and your using are the wrong way round. You need to have the using to set the streamwriter, then do a loop (foreach) wihtin this to write the lines.
( this is rough hack of your code. )
试试这个....
try this....
这将每次用用户的一行重写该文件。
移动
foreach
周围的 open 语句,将所有用户名写入文件。This will rewrite to the file each time with a single line with the user.
Moving the open statement around the
foreach
to write all user names out to file.使用
File.WriteAllLines
可以非常轻松解决这个问题This can be very easily solved with
File.WriteAllLines
WriteLine 调用附加一个 CRLF,但您的 String.Format 包含一个额外的 CRLF。因此,每个用户将获得两行。
并且 using 语句需要位于 foreach 之外(ist 中的字符串 user)。
The WriteLine call appends a CRLF, but your String.Format is including an additional CRLF. So you will get two lines per user.
And the using statement needs to be outside of your foreach (string user in ist).