开发者

MultiColumn Listview items to File

开发者 https://www.devze.com 2023-04-13 09:51 出处:网络
I\'m working on my small application and I need to get items from listview and write 开发者_StackOverflowthem to txt file. Does anybody know how to do it? Please help me.

I'm working on my small application and I need to get items from listview and write 开发者_StackOverflowthem to txt file. Does anybody know how to do it? Please help me.

=================================================================================

For example: In listview

Name     | Password
Me       | YesNoYesNo
You      | NoYesNoYEs
Everybody| YESNoYESNo

In file:

ME|YesNoYesNo \r\n
You|NoYESNoYES \r\n

...

EDIT: Guys I forgot tell you that I'm using WPF. Sorry.


Here's an old school way of doing it and getting your separators included in the file:

using (StreamWriter writer = new StreamWriter(@"C:\Desktop\test.txt"))
{
    StringBuilder line = new StringBuilder();
    foreach (ListViewItem item in listView1.Items)
    {
        line.Clear();
        for (int i=0; i<item.SubItems.Count; i++)
        {
            if (i > 0)
                line.Append("|");
            line.Append(item.SubItems[i].Text);
        }
        writer.WriteLine(line);
    }
}


HOw about this ...I hope it will helps you....

On whatever event will trigger your save: open the file, iterate through the list content writing the text to the file and then close the file. The close can of course be done via using:

using (var tw = new StreamWriter(filename)) {
     foreach (ListViewItem item in listView.Items) {
     tw.WriteLine(item.Text); 
  }
}


You can write both line or byte wise, close the file otherwise sometimes the change won't reflect:

string tmppath = @".....\temp.txt";
FileStream writefile = new FileStream(tmppath, FileMode.Open, FileAccess.Write);
//StreamWriter sw = new StreamWriter(writefile);//To write line
if (File.Exists(tmppath))
{
    foreach (ListViewItem itm in listView1.Items)
    {
        writefile.Write(uniEncoding.GetBytes(f.Text), 0,uniEncoding.GetByteCount(itm.Text));
        //OR
        //sw.WriteLine(itm.Text);
    }
writefile.Close();
//OR
//sw.Close();
0

精彩评论

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