开发者

Writing a comma separated string line by line to a file

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)
            {
      开发者_StackOverflow中文版          using (StreamWriter whiteList = new StreamWriter(cleanDir + @"\white-list.txt"))
                {
                    whiteList.WriteLine(String.Format("{0}\r\n", user));
                }
            }
        }


I would swap your using and for loop around. And remove the new line characters

using (StreamWriter whiteList = new StreamWriter(cleanDir + @"\white-list.txt"))
{
    foreach (string user in list)
    {
        whiteList.WriteLine(user);
    }
}


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.

if (chkWhiteList.Checked)
    {
        string rawUser = rtboxWhiteList.Text;
        string[] list = rawUser.Split(new char[] { ',' });

        using (StreamWriter whiteList = new StreamWriter(cleanDir + @"\white-list.txt"))
        {
            foreach (string user in list)
            {
                whiteList.WriteLine(String.Format("{0}\r\n", user));
            }
        }
    }

( this is rough hack of your code. )


try this....

    if (chkWhiteList.Checked)
    {
        string rawUser = rtboxWhiteList.Text;
        string[] list = rawUser.Split(new char[] { ',' });

        using (StreamWriter whiteList = new StreamWriter(cleanDir + @"\white-list.txt"))
            {
                foreach (string user in list)
                {
                     whiteList.WriteLine(String.Format("{0}\r\n", user));
                }

            }
    }


        {
            using (StreamWriter whiteList = new StreamWriter(cleanDir + @"\white-list.txt"))
            {
                whiteList.WriteLine(String.Format("{0}\r\n", user));
            }
        }

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.


This can be very easily solved with File.WriteAllLines

string rawUser = rtboxWhiteList.Text;            
string[] list = rawUser.Split(',');
System.IO.File.WriteAllLines(cleanDir + @"\white-list.txt", list);


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜