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();
Related
I am totally new to C#, I want to read a CSV file line by line and write to another CSV file while writing I need to skip the first 4 lines, Can anyone help me with this?
Thanks in advance.
Below is the code I tried.
int index = 0;
using (StreamWriter writer = new StreamWriter(File.OpenWrite("D:\\work\\POCs\\POC_RESOURCES\\Pricing_Files\\index-edited-ap-east-1.csv")))
using (StreamReader reader = new StreamReader(File.OpenRead("D:\\work\\POCs\\SPOT_POC_RESOURCES\\Pricing_Files\\index-ap-east-1.csv")))
{
while (!reader.EndOfStream)
{
Console.WriteLine(index);
string line = reader.ReadLine();
writer.WriteLine(line);
}
}
To Skip the first 4 lines of the input file you need to read a line on every iteration of the while loop
using (var writer = new StreamWriter(File.OpenWrite("D:\\work\\POCs\\POC_RESOURCES\\Pricing_Files\\index-edited-ap-east-1.csv")))
using (var reader = new StreamReader(File.OpenRead("D:\\work\\POCs\\SPOT_POC_RESOURCES\\Pricing_Files\\index-ap-east-1.csv")))
{
var index = 0;
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (index > 4)
{
Console.WriteLine(index);
writer.WriteLine(line);
}
index++;
}
}
I am using the file helpers library to construct a csv but I need to create one csv file per record.
var engine = new FileHelperEngine(typeof(SalesOrders));
int count = 0;
foreach (SalesOrders item in purchaseOrder)
{
count++;
string fileName = "SalesOrder_" + item.OrderNumber.ToString() + ".csv";
var feng = new FileHelperEngine<SalesOrders>();
string str1 = feng.WriteString(purchaseOrder);
List<SalesOrdersItems> _orderItemsForExport = SopOrderItems.Where(a => a.ORDER_NUMBER.ToString() == item.OrderNumber).ToList();
}
However this line
string str1 = feng.WriteString(purchaseOrder);
Is printing out all the contents instead of the item per csv. I think its just my logic is not correct.
foreach (SalesOrders item in purchaseOrder)
{
using (StreamWriter sw = new StreamWriter($"SalesOrder_{item.OrderNumber.ToString()}.csv"))
{
var lines = TakeAllStuffFrom(item); // like a collection of $"{SalesOrder.FirstField.Trim()};{SalesOrder.SecondField.Trim()}";
foreach (var line in lines)
{
sw.WriteLine(line);
}
}
}
Write example of what you expect to appear in your csv file and we will figure something out :)
I need to check if the string exists in a text file and if it does then proceed. if not, it will display a MessageBox saying that the ID does not exist.
In my previous question, I tried to check if "testfile.txt" contains the string inputted by the user in TextBox1 then copy the line which contains the string into a new textfile. Using the approach that has been suggested, here's a snippet of what I have so far:
string emp_profile = #"EmployeeData.txt"; //file to be checked
string endata = #"EndData.txt"; //terminated employees data file
string end_tdata = #"end_tdata.txt"; //holds sample's data
//validates if eid exists and if it exists copies data of sample
//plus txt_end.Text into temporary data file
string[] dataline = File.ReadAllLines(emp_profile);
using (StreamWriter w = File.AppendText(end_tdata))
{
foreach (var line in dataline)
{
if (line.Contains(txt_un.Text))
{
w.WriteLine(txt_end.Text + "," + line);
w.Close();
}
}
}
string end_holddata = #"end_holddata.txt";
//read original file
string[] raw_data = File.ReadAllLines(endata);
using (StreamWriter r = File.AppendText(end_holddata))
{
foreach (var line in raw_data)
{
if (!line.Contains(txt_un.Text))
r.WriteLine(line);
}
r.Close();
}
//delete original file
File.Delete(endata);
//creates new data file with old data path
//and copies the temporary data held testdata
using (Stream input = File.OpenRead(end_holddata))
using (Stream output = new FileStream(endata, FileMode.Append,
FileAccess.Write, FileShare.None))
{
input.CopyTo(output);
}
//appends new data of sample into the newly created data file
using (Stream input = File.OpenRead(end_tdata))
using (Stream output = new FileStream(endata, FileMode.Append,
FileAccess.Write, FileShare.None))
{
input.CopyTo(output);
}
DialogResult result = MessageBox.Show("Data has been recorded.");
//clears all temporary files
if (result == DialogResult.OK)
{
File.Delete(end_holddata);
File.Delete(end_tdata);
}
What I'm trying to do here is that I'm copying the data from the "emp_profile.txt that does not contain the txt_un.Text into "end_holddata" and copy the line that contains the input into a different file end_tdata.txt, delete the old datafile to clear contents then merge the data into a new data with the same pathfile as the old one. Afterwards, the temporary data files would be deleted.
I tried enclosing the above snippet within this but it's not working the way I want it to.
string[] dataline = File.ReadAllLines(emp_profile);
for (int i = 0; i < dataline.Length; i++)
{
if (dataline[i].Contains(txt_un.Text))
{
//code snippet here
}
else
MessageBox.Show("ID does not exist!");
}
Any help would appreciated! Thank you in advance!
I'm trying to replace a file line with another one.
here's my block of code
string text = readWholeFile(fileName);
text = text.Replace(oldLine, newLine);
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
using (var isoFileStream = new IsolatedStorageFileStream(fileName,
FileMode.OpenOrCreate, FileAccess.Write, myStore))
{
using (var isoFileWriter = new StreamWriter(isoFileStream))
{
isoFileWriter.WriteLine(text);
isoFileWriter.Close();
}
isoFileStream.Close();
the problem is that the Line is only replaced the exact number of newLine characters.For example if OldLine was 1234567890 and newLine is asd. The file operation gives output something like this
asd
4567890
here readWholeFile method reads the whole file. and oldLine ,newLine is the method string parameter.
This piece of code works as expected:
string text = "1234567890\n1234567891\n1234567892";
var rText = text.Replace("1234567890", "asd");
Console.WriteLine(rText);
Console.ReadKey();
The output is:
asd
1234567891
1234567892
So, it's obvious that you're problem isn't with the String.Replace method.
You can use a simple code to "read the whole file":
string[] text = File.ReadAllLines(filename);
StringBuilder str = new StringBuilder();
foreach (string s in text)
str.AppendNewLine(s);
And than,
var rText = str.ToString().Replace(oldLine, newLine);
And finally, save everything to file again:
File.WriteAllText(outputFile, rText);
EDIT
Also, the following code works:
string text = "1234567890\n1234567891\n1234567892";
var rText = text.ToString().Replace("1234567890", "asd");
using (var isoFileStream = new FileStream("output.txt",
FileMode.Create, FileAccess.Write))
{
using (var isoFileWriter = new StreamWriter(isoFileStream))
{
isoFileWriter.Write(rText);
}
}
The output, as expected, was:
asd
1234567891
1234567892
But I found that the following caused problems:
using (var isoFileStream = new FileStream("output.txt",
FileMode.OpenOrCreate, FileAccess.Write))
{
using (var isoFileWriter = new StreamWriter(isoFileStream))
{
isoFileWriter.Write(rText);
}
}
The situation that this caused problems was when the file already exists with the following content:
1234567890
1234567891
1234567892
The output in the file was:
asd
1234567891
1234567892
67892
If instead of File.OpenOrCreate the file mode is changed to File.Create, the problem disappears.
EDIT
I didn't used "IsolatedStorageFile" just because I'm not testing on a SilverLight context nor using ClickOnce to deploy, and so it won't work
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);
}
}
}
}
}