Hi all,
I am trying to get out put in the folder . The folder is created but the text file is not visible.What is wrong with this code. Here goes the code:

private void savetxt()
        {
            try
            {
                //m_stockInfolist is nothing but the listview control name  
                string[] st = new string[m_StockInfoList.Columns.Count];
                DirectoryInfo di = new DirectoryInfo(@"c:\Extraction\");
                if (di.Exists == false)
                    di.Create();
                StreamWriter sw = new StreamWriter(@"c:\Extraction\file.txt", false);
                sw.AutoFlush = true;
                for (int col = 0; col < m_StockInfoList.Columns.Count; col++)
                {
                    sw.Write("\t" + m_StockInfoList.Columns[col].Text.ToString());
                }
                int rowIndex = 1;
                int row = 0;
                string st1 = "";
                for (row = 0; row < m_StockInfoList.Items.Count; row++)
                {
                    if (rowIndex <= m_StockInfoList.Items.Count) rowIndex++;
                    st1 = "\n";
                    for (int col = 0; col < m_StockInfoList.Columns.Count; col++)
                    {
                        st1 = st1 + "\t" + "'" + m_StockInfoList.Items[row].SubItems[col].Text.ToString();
                    }
                    sw.WriteLine(st1);
                }
                sw.flush();
                sw.Close();
            }

            {
            }

Anyone there to help me out .
Thanks

Recommended Answers

All 16 Replies

Andy,

other than a couple small errors, it worked for me.
Here is the code I used with corrections:

private void savetxt()
        {
            // Got rid of "try" because it did not have the rest of it in your sample.
            //m_stockInfolist is nothing but the listview control name 
            //string[] st = new string[m_StockInfoList.Columns.Count];
            DirectoryInfo di = new DirectoryInfo(@"c:\Extraction\");
            if (!di.Exists) // Changed to use a boolean comparitor rather than a boolean equate
                di.Create();
            StreamWriter sw = new StreamWriter(@"c:\Extraction\file.txt", false);
            sw.AutoFlush = true;
            for (int col = 0; col < m_StockInfoList.Columns.Count; col++)
            {
                sw.Write("\t" + m_StockInfoList.Columns[col].Text.ToString());
            }
            //int rowIndex = 1; // not used
            //int row = 0;      // define in for..loop instead of here
            string st1;         // assignment not required
            for (int row = 0; row < m_StockInfoList.Items.Count; row++)
            {
                //if (rowIndex <= m_StockInfoList.Items.Count) rowIndex++; Not used
                st1 = "\r\n"; // Needed a Line Return
                for (int col = 0; col < m_StockInfoList.Columns.Count; col++)
                {
                    // used concat operator, and string format to get things positioned right
                    st1 += string.Format("\t'{0}'", m_StockInfoList.Items[row].SubItems[col].Text.ToString());
                }
                sw.WriteLine(st1);
            }
            sw.Flush();  //sw.flush(); Flush .. not flush (case sensitive), besides with autoflush on, this is redundant
            sw.Close();
        }

// Jerry

Thanks Jerry for quick reply. If I want to save only first three columns then how it will be done.

for (int col = 0; col < 3; col++)

Can you help me Jerry? I got stuck with write the data in the ListView to text file. I try to write it to something like this:

Header1    Header2
item1      subItem1
......     .........

I use the text above but it will create an empty between 2 item data. And i don't want to use ' ' , instead using semicolon ",". When i try to use semicolon, it turns out to have another semicolon at the end of the line. So how can i fix that? Also I'm looking loading text file to ListView.

Okay, so you want to have a comma seperated values file (CSV).
A common task, What I typically do is start the string with a comma
then append / concatenate all of the values ALSO including a comma so that all values are started with a comma. Now once all of the values have been appened to the line, simply take the substring starting at index 1.

for (int col = 0; col < m_StockInfoList.Columns.Count; col++)
{
    // used concat operator, and string format to get things positioned right
   // Note that each value starts with a comma.
    st1 += string.Format(",{0}", m_StockInfoList.Items[row].SubItems[col].Text.ToString());
}
st1 = st1.SubString(1); // get rid of the very first comma
sw.WriteLine(st1);

// Jerry

I did that and had a problem with the Substring. The 1st comma didn't disappear. And then it still had an empty line between 2 data like

item1

item2

and that is not i want. All I want is like this one

Header1   Header2
item1,    subitem1
item2,    subitem2
.......   ........

You have something wrong, please post your current code that handles this task and I will take a look.

My code:

private void saveButton_Click(object sender, EventArgs e)
        {
            FileStream file = new FileStream(@"C:\sample.playist", FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(file);
            for (int col = 0; col < listView1.Columns.Count; col++)
            {
                sw.Write(" " + listView1.Columns[col].Text.ToString() + "\t");
            }
            string st1;
            for (int row = 0; row < listView1.Items.Count; row++)
            {
                st1 = "\r\n";
                for (int col = 0; col < listView1.Columns.Count; col++)
                {
                    // used concat operator, and string format to get things positioned right
                    // Note that each value starts with a comma.
                    st1 += string.Format(",{0}", listView1.Items[row].SubItems[col].Text.ToString());
                }
                st1 = st1.Substring(0); // get rid of the very first comma
                sw.WriteLine(st1);
            }
            sw.Flush();
            sw.Close();
        }

SubString didn't work because you are using a 0 when you should be using a 1.
Looking further while to correct that.... back in a bit.
// Jerry

SubString didn't work because you are using a 0 when you should be using a 1.
Looking further while to correct that.... back in a bit.
// Jerry

Using 1 at Substring does not work too. I show you example of my result. Example like I have 2 items in the ListView.

ID     Name
23,    45
56,    78

But the result is not what i want above, the result is below there.

ID	 Name	
,23,45

,56,78

You can see the empty line between that and that when i use substring(0). When i used Substring(1), here is result:

ID	 Name	,232,4545
,232,45754

No empty string but the first item is in the line of the header.

Untested modified version

private void saveButton_Click(object sender, EventArgs e)
        {
            string st1= string.Empty;
            FileStream file = new FileStream(@"C:\sample.playist", FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(file);
            for (int col = 0; col < listView1.Columns.Count; col++)
            {
                st1 += (" " + listView1.Columns[col].Text.ToString() + "\t");             
            }
            sw.WriteLine(st1);
            st1 = string.Empty;

            for (int row = 0; row < listView1.Items.Count; row++)
            {
                //st1 = "\r\n"; the writeline will take care of this
                for (int col = 0; col < listView1.Columns.Count; col++)
                {
                    // used concat operator, and string format to get things positioned right
                    // Note that each value starts with a comma.
                    st1 += string.Format("{0},\t", listView1.Items[row].SubItems[col].Text.ToString());
                }
                st1 = st1.Substring(0, st1.Length - 2); // remove the last comma and tab chars
                sw.WriteLine(st1);
            }
            sw.Flush();
            sw.Close();
        }

// Jerry

It works with the tab and first comma, also with an empty line, but there still error, 2 duplicate first item.

ID Name
565, 87
565, 8754745, 78078

The input is

ID   Name	
565, 87
54745, 8078

Here is the Tested, and working version

private void saveButton_Click(object sender, EventArgs e)
        {
            string st1 = string.Empty;
            FileStream file = new FileStream(@"C:\Titan\sample.playist", FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(file);
            for (int col = 0; col < listView1.Columns.Count; col++)
            {
                st1 += (" " + listView1.Columns[col].Text.ToString() + "\t"); // added \r\n
            }
            sw.WriteLine(st1);
            st1 = string.Empty;
            for (int row = 0; row < listView1.Items.Count; row++)
            {
                st1 = string.Empty;
                for (int col = 0; col < listView1.Columns.Count; col++)
                {
                    st1 += string.Format("{0},\t", listView1.Items[row].SubItems[col].Text.ToString());
                }
                st1 = st1.Substring(0, st1.Length - 2);
                sw.WriteLine(st1);
            }
            sw.Flush();
            sw.Close();
        }

// Jerry
Mark as solved if this works for you.

Thank for help. It works. Yeah. Can I ask you 1 question. So how we can populate the ListView with this file? My thought was we have to use delighted method of the reader for the comma, and then remove the header, and then populate each of them.

To read the file you created, yes, discard the first line read (the header), then for each new line read, split the values based on the comma, and don't forget to replace the Tab character:

private void button2_Click(object sender, EventArgs e)
        {
            char[] delim = new char[2]{',','\t'};
            listView1.Items.Clear();
            TextReader file = new StreamReader(@"C:\sample.playist");
            file.ReadLine();

            string line = file.ReadLine();
            string[] values;
            while (!string.IsNullOrEmpty(line)) 
            {
                values = line.Split(delim,StringSplitOptions.RemoveEmptyEntries);
                ListViewItem item = new ListViewItem(values[0]);
                for (int i = 1; i < values.Length; i++)
                    item.SubItems.Add(values[i]);
                listView1.Items.Add(item);
                line = file.ReadLine();
            }
            file.Close();
        }

Thank you very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.