How to save the ListView contents to a text file? - c#

How to save the ListView contents (including the ColumnHeaders) to a text file?
thanks.

There is nothing in .NET that will do this for you, you need to do the work yourself.
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);
}
}

If you want to export all the subitems you must use this code:
StringBuilder sb;
if (listView.Items.Count > 0)
{
// the actual data
foreach (ListViewItem lvi in listView.Items)
{
sb = new StringBuilder();
foreach (ListViewItem.ListViewSubItem listViewSubItem in lvi.SubItems)
{
sb.Append(string.Format("{0}\t", listViewSubItem.Text));
}
sw.WriteLine(sb.ToString());
}
sw.WriteLine();
}

This should work 100%, I made this for a project of mine.
I know this is 4 years too late but here it is.
private void export2File(ListView lv, string splitter)
{
string filename = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "SaveFileDialog Export2File";
sfd.Filter = "Text File (.txt) | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
filename = sfd.FileName.ToString();
if (filename != "")
{
using (StreamWriter sw = new StreamWriter(filename))
{
foreach (ListViewItem item in lv.Items)
{
sw.WriteLine("{0}{1}{2}", item.SubItems[0].Text, splitter, item.SubItems[1].Text);
}
}
}
}
}

Related

How can I add 2 cells in a CSV file in WPF?

I use the OpenFileDialog in my WPF program to give the user the option to select a .csv file and read it into the program. Now I have the path and everything from the file that the user wants and now I want to add 2 more cells to the Excel file after a button click. How should I change it so that as soon as the button is pressed, 2 columns and cells are added to the previously imported Excel file. Here is my OpenFileDialog how I get the file OpenFileDialog::
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.Filter = "CVS (*.cvs)|*.csv|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
openFileDialog.Title = "CVS Datei Auswählen zum Konvertieren";
if (openFileDialog.ShowDialog() == true)
{
foreach (string filename in openFileDialog.FileNames)
{
tbxFiles.Items.Add(System.IO.Path.GetFileName(filename));
string temp;
var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
temp = streamReader.ReadToEnd();
test = temp;
}
}
}
SaveFileDialog:
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "CVS (*.cvs)|*.csv|All files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
List<String> liste = new List<String>();
// test = test + "Hallo;";
//File.WriteAllText(dialog.FileName, test);
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(test);
while ((line = file.ReadLine()) != null)
{
if (counter == 0)
{
line += ",column1,column2";
}
else
{
line += $",{""},{""}";
}
counter++;
}
file.Close();
}
In my "test" string I have now read in what is in the cvs file via streamreader. This is what the cvs Header looks like:
Picture 1
and so how i want it look like after my C# change:
Picture2
tbxFiles = my TextBox where the path of the selected file is shown.
So how can I add additional Excel columns with associated cells to the imported Excel file in Code Behind 2?
There you go:
....
while ((line = file.ReadLine()) != null)
{
if (counter == 0)
{
line += ",column1,column2";
}
else
{
line += $",{value1},{value2}";
}
counter++;
}
...

How to create the zip file from the selected rows of datagridview in c#

I am displaying certain elements from .xml files into a DataGridView and it's working fine.
Here is the code to select the xml files
//Browse Folder
private void Btn_SelectFolder_Click(object sender, EventArgs e)
{
try
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK)
{
DataTable dt = new DataTable();
dt.Rows.Clear();
dt.Columns.Add("Select", typeof(bool));
dt.Columns.Add("File_Name");
dt.Columns.Add("Vendor_Name");
dt.Columns.Add("Vendor_ID");
dt.Columns.Add("Date_Range", typeof(DateTime));
lbl_Path.Text = fbd.SelectedPath;
string[] files = Directory.GetFiles(fbd.SelectedPath, "*.xml");
XmlDocument doc = new XmlDocument();
XmlNodeList nodes = doc.GetElementsByTagName("cfdi:Emisor");
XmlNodeList nodes1 = doc.GetElementsByTagName("cfdi:Comprobante");
foreach (string tot_file in files)
{
doc.Load(tot_file);
string FileName = Path.GetFileNameWithoutExtension(tot_file);
for (int i = 0; i < nodes.Count; i++)
{
string Name = nodes[i].Attributes["Nombre"].Value;
string ID = nodes[i].Attributes["Rfc"].Value;
string Date = nodes1[i].Attributes["Fecha"].Value;
DataRow row = dt.NewRow();
row["File_Name"] = FileName;
row["Vendor_Name"] = Name;
row["Vendor_ID"] = ID;
row["Date_Range"] = Date;
dt.Rows.Add(row);
}
}
XML_Grid.DataSource = dt;
txt_FileName.ReadOnly = false;
txt_Name.ReadOnly = false;
txt_ID.ReadOnly = false;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Now what i want is to select the rows from DataGridView and create the zip file of selected files.
I have tried this code to create the zip file:
//Create Zip
private void Btn_SaveZip_Click(object sender, EventArgs e)
{
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string folderToZip = lbl_Path.Text;
string zipFile = saveFileDialog1.FileName + ".zip";
using (ZipArchive zipArchive = ZipFile.Open(zipFile, ZipArchiveMode.Create))
{
DirectoryInfo di = new DirectoryInfo(folderToZip);
FileInfo[] filesToArchive = di.GetFiles();
if (filesToArchive != null && filesToArchive.Length > 0)
{
foreach (FileInfo fileToArchive in filesToArchive)
{
zipArchive.CreateEntryFromFile(fileToArchive.FullName, fileToArchive.Name, CompressionLevel.Optimal);
}
}
}
MessageBox.Show("Zip File Successfully Created", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Question);
}
}
The above code is working fine and creating zip file But it's directly checking the files from the path and creating zip file of that folder.
How to select the files from DataGridview not directly from the folder and create the zip file of selected files.
My Form:
Any help would be helpful for me, I've been trying to get this working for hours now.
If I understood your problem correctly, you want to save only those files where the Select column is checked in your data grid into one zip file.
If so, the following modification to your Zip save routine can help you with that:
using (ZipArchive zipArchive = ZipFile.Open(zipFile, ZipArchiveMode.Create))
{
List<FileInfo> filesToArchive = new List<FileInfo>();
DirectoryInfo di = new DirectoryInfo(folderToZip);
// loop through all of the rows in the data grid
foreach (DataGridViewRow row in XML_Grid.Rows)
{
DataRowView rowView = row.DataBoundItem as DataRowView;
if (rowView == null) continue; // new row or not bound, ignore
var selectedValue = rowView["Select"]; // get the value for the select column
if (selectedValue == DBNull.Value || selectedValue == null || !(bool)selectedValue) // ignore null or false
continue;
string fileName = rowView["File_Name"].ToString(); // get the file name
var files = di.GetFiles(fileName + ".*"); // we had no extension so search the folder to get the full path
filesToArchive.AddRange(files); // add those file(s) to the list to archive
}
if (filesToArchive != null && filesToArchive.Count > 0)
{
foreach (FileInfo fileToArchive in filesToArchive)
{
zipArchive.CreateEntryFromFile(fileToArchive.FullName, fileToArchive.Name, CompressionLevel.Optimal);
}
}
}

export content of Listview(s) to CSV file

I have 5 listviews that I want to export it out into one CSV file.
This is my 5 listview
In the listview, you can see that the Date Time is the same for all 6 listviews.
So I was able to export the first listview into a CSV File.
saveFileDialog1.Filter = "csv files (*.csv)|*.csv";
saveFileDialog1.FileName = "logs";
saveFileDialog1.Title = "Export to Excel";
StringBuilder sb = new StringBuilder();
foreach (ColumnHeader ch in listView1.Columns)
{
sb.Append(ch.Text + ",");
}
sb.AppendLine();
foreach (ListViewItem lvi in listView1.Items)
{
foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
{
if (lvs.Text.Trim() == string.Empty)
sb.Append(" ,");
else
sb.Append(lvs.Text + ",");
}
sb.AppendLine();
}
DialogResult dr = saveFileDialog1.ShowDialog();
if (dr == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFileDialog1.FileName);
sw.Write(sb.ToString());
sw.Close();
this.Close();
}
Now I want to export the remaining other 4 listview into the same CSV file where the first colomn will be the Date Time which is the same for all 5 listview.
How do I go about doing so?
Complete code to accomplish your task
class ListViewToCSV
{
public static void ListViewToCSV(ListView listView, string filePath, bool includeHidden)
{
//make header string
StringBuilder result = new StringBuilder();
WriteCSVRow(result, listView.Columns.Count, i => includeHidden || listView.Columns[i].Width > 0, i => listView.Columns[i].Text);
//export data rows
foreach (ListViewItem listItem in listView.Items)
WriteCSVRow(result, listView.Columns.Count, i => includeHidden || listView.Columns[i].Width > 0, i => listItem.SubItems[i].Text);
File.WriteAllText(filePath, result.ToString());
}
private static void WriteCSVRow(StringBuilder result, int itemsCount, Func<int, bool> isColumnNeeded, Func<int, string> columnValue)
{
bool isFirstTime = true;
for (int i = 0; i < itemsCount; i++)
{
if (!isColumnNeeded(i))
continue;
if (!isFirstTime)
result.Append(",");
isFirstTime = false;
result.Append(String.Format("\"{0}\"", columnValue(i)));
}
result.AppendLine();
}
}

c# Write DataTable Rows in txt File

I have for like 40 rows on My DataTable Displayed in a DataGridView
i'm confused why my method Saves Only One Row in the TextFile :
private void SaveBtn_Click(object sender, EventArgs e)
{
String outputFile;
List<String> ListData = new List<String>();
using (SaveFileDialog sfd = new SaveFileDialog())
{
sfd.Filter = "Txt File|*.Txt";
if (sfd.ShowDialog() != DialogResult.OK)
return;
outputFile = sfd.FileName;
}
DataTable tb = pw.SavedInfo(User_info.UserID);
for (int i = 0; i < tb.Rows.Count; i++)
{
ListData.Add("Name==> " + tb.Rows[i][1].ToString() + " LastName ==> " + tb.Rows[i][2].ToString() + " Email ==> " + tb.Rows[i][3].ToString() );
}
foreach (String s in ListData)
{
using (TextWriter Tw = new StreamWriter(outputFile))
{
Tw.WriteLine(s);
}
}
}
Did i missed something ? cause it was a really long day to keep being focused
Use the same StreamWriter:
using (TextWriter Tw = new StreamWriter(outputFile))
{
foreach (String s in ListData)
{
Tw.WriteLine(s);
}
}
or use the constructor that takes a bool for "append":
foreach (String s in ListData)
{
using (TextWriter Tw = new StreamWriter(outputFile, true))
{
Tw.WriteLine(s);
}
}
File.WriteAllLines(outputFile, lisData);
Use this to write in the file. File.WriteAllLines Documentation

MultiColumn Listview items to File

I'm working on my small application and I need to get items from listview and write them 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();

Categories

Resources