Need file read in from form load - c#

I am using a listview, and trying to populate using a file.
I need the file to be read in as soon as the form starts.
private void mainForm_Load(object sender, EventArgs e)
{
//get file read in
if (File.Exists("../../MealDeliveries.txt"))
{
StreamReader sr = new StreamReader("../../MealDeliveries.txt");
//first line is delivery name
string strDeliveryName = sr.ReadLine();
do
{
//other lines
Delivery d = new Delivery(strDeliveryName, sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine());
mainForm.myDeliveries.Add(d);
//check for further values
strDeliveryName = sr.ReadLine();
//stop if no more values
} while (strDeliveryName != null);
displayDeliveries();
}
}
private void displayDeliveries()
{
lstDeliveryDetails.Items.Clear();
foreach (Delivery d in mainForm.myDeliveries)
{
lstDeliveryDetails.Items.Add(d.DeliveryName);
}
}
The listview isn't displaying anything, although the file is definately there!

Yes, it should assuming that the file is in the place you think it is. Are you positive that the file exists?
Try this. It will at least confirm whether or not the file is found.
private void mainForm_Load(object sender, EventArgs e)
{
string fileName = #"..\..\MealDeliveries.txt";
if (!File.Exists(fileName))
{
MessageBox.Show("File not found!");
return;
}
using (StreamReader sr = new StreamReader(fileName))
{
//first line is delivery name
string strDeliveryName = sr.ReadLine();
while (strDeliveryName != null)
{
//other lines
Delivery d = new Delivery(strDeliveryName, sr.ReadLine(),
sr.ReadLine(), sr.ReadLine(),
sr.ReadLine(), sr.ReadLine(),
sr.ReadLine());
mainForm.myDeliveries.Add(d);
//check for further values
strDeliveryName = sr.ReadLine();
}
}
displayDeliveries();
}
Another thing to watch out for is reading lines in as a string to pass to your business object (Delivery). You might find it better to use some sort of serialization format provided by XmlSerializer or one of the file formats supported by Marcos Meli's FileHelpers library. Either way, something more robust than reading in strings would be desirable.

Maybe it will work but you also need to wrap IDisposables with using. Like this:
using (StreamReader sr = new StreamReader("../../MealDeliveries.txt"))
{
//first line is delivery name
string strDeliveryName = sr.ReadLine();
do
{
//other lines
Delivery d = new Delivery(strDeliveryName, sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine());
mainForm.myDeliveries.Add(d);
//check for further values
strDeliveryName = sr.ReadLine();
//stop if no more values
} while (strDeliveryName != null);
displayDeliveries();
}

Related

Replace specific data in a csv file

I am trying to replace a specific data field in my csv file but am having issues.
My csv file is structured like:
user, password, role, id,
1, abc, 2, 3
2, def, 2, 4
3, ghi, 5, 5
I can read the file fine but when I want to replace a password using a textbox and button in a windows form I am having issues.
private void resetBtn_Click(object sender, EventArgs e)
{
var encoding = Encoding.GetEncoding("iso-8859-1");
var csvLines = File.ReadAllLines("C:\\Users\\hughesa3\\Desktop\\test environment\\users.csv", encoding);
foreach (var line in csvLines)
{
var values = line.Split(',');
if (values[0].Contains(form2value))
{
values[1] = confirmPass.Text;
}
}
}
Form2value is their username, So what im trying do is: If the first column contains what was entered in form2value it will go to the 2nd column of that row.
I have tried this
var values = line.Split(',');
if (values[0].Contains(form2value))
{
MessageBox.Show(values[1]);
values[1] = confirmPass.Text;
MessageBox.Show(values[1]);
}
}
Just to see if the value is changing and it is but it is also displaying every value[1] when i only want it to if form2value was found.
I tried to explain this as best as I could but if anyone needs more info please let me know.
Does anybody know what I am doing wrong ?
Life would be easier for you if you used a data table..........
Here is an excerp...
DT is a DataTable.
Split the first line of your file and us dt.Columns.Add to add the column headings....
private void AddDataToDataTable()
{
using (StreamReader sr = new StreamReader(new MemoryStream(this.FileContents)))
{
//Igone headings & blank Lines
string line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
//If blank line then skip line
if (line == string.Empty)
{
continue;
}
dt.Rows.Add(line.Split(this.Delimeter));
}
}
}
Hope this helps
You're changing the values internal array you use in your code, not the file itself. In fact you're not writing the file anywhere, just reading it.
You'll need to: Read the file, get the line where the username is (if it exists), then write that specific line with the password.
Here's how you can do it:
private void resetBtn_Click(object sender, EventArgs e)
{
var encoding = Encoding.GetEncoding("iso-8859-1");
var csvLines = File.ReadAllLines("C:\\Users\\hughesa3\\Desktop\\test environment\\users.csv", encoding);
for (int i = 0; i < csvLines.Length; i++)
{
var values = csvLines[i].Split(',');
if (values[0].Contains(form2value))
{
values[1] = confirmPass.Text;
using (FileStream stream = new FileStream("C:\\Users\\hughesa3\\Desktop\\test environment\\users.csv", FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(stream, encoding))
{
for (int currentLine = 0; currentLine < csvLines.Length; ++currentLine)
{
if (currentLine == i)
{
writer.WriteLine(string.Join(",", values));
}
else
{
writer.WriteLine(csvLines[i]);
}
}
writer.Close();
}
stream.Close();
}
}
}
}

C# CSV file still open when appending

I'm trying to allow the user to add another entry to the CSV file my program is building. It is building it out of a database like this:
public void CreateCsvFile()
{
var filepath = #"F:\A2 Computing\C# Programming Project\ScheduleFile.csv";
var ListGather = new PaceCalculator();
var records =
from record in ListGather.NameGain()
.Zip(ListGather.PaceGain(),
(a, b) => new { Name = a, Pace = b })
group record.Pace by record.Name into grs
select String.Format("{0},{1}", grs.Key, grs.Average()); //reduces the list of integers down to a single double value by computing the average.
File.WriteAllLines(filepath, records);
}
I then am calling it into a datagridview like this:
private void button2_Click(object sender, EventArgs e)
{
CreateExtFile CsvCreate = new CreateExtFile();
CsvCreate.CreateCsvFile();
return;
}
private void LoadAthletes()
{
string delimiter = ",";
string tableName = "Schedule Table";
string fileName = #"F:\A2 Computing\C# Programming Project\ScheduleFile.csv";
DataSet dataset = new DataSet();
StreamReader sr = new StreamReader(fileName);
dataset.Tables.Add(tableName);
dataset.Tables[tableName].Columns.Add("Athlete Name");
dataset.Tables[tableName].Columns.Add("Pace Per Mile");
string allData = sr.ReadToEnd();
string[] rows = allData.Split("\r".ToCharArray());
foreach (string r in rows)
{
string[] items = r.Split(delimiter.ToCharArray());
dataset.Tables[tableName].Rows.Add(items);
}
this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
}
A button opens a window which contains fields to add a new entry to the csv file. This is how I am doing this:
private void AddToScheduleBtn_Click(object sender, EventArgs e)
{
string FileName = #"F:\A2 Computing\C# Programming Project\ScheduleFile.csv";
string AthleteDetails = textBox1.Text + "," + textBox2.Text;
File.AppendAllText(FileName, AthleteDetails);
AddToSchedule.ActiveForm.Close();
}
Although this works once, When I try and add another entry to my csv file again it says it is open in another process and the program crashes. When the data first appears in my datagridview, there is an empty row at the bottom which there shouldn't be. What is the best way of allowing me to re-use the process so I can append to the file more than once?
I think your line,
StreamReader sr = new StreamReader(fileName);
has the file opened. You want to do the following:
string allData = sr.ReadToEnd();
sr.Close();
sr.Dispose();
I didn't build your code, but this error is usually raised when the file reader was not closed :)
You should add sr.close() to your LoadAthletes method or implement the using for an automatic closing:
using (StreamReader sr = new StreamReader(fileName))
{
allData = sr.ReadToEnd();
}
Or use the following method :
allData = File.ReadAllText(fileName);
Hope this Help
For more information see this question do-i-need-to-explicitly-close-the-streamreader-in-c-sharp-when-using-it-to-load

Parsing CSV data

I am trying to parse a CSV file with data with no luck, i have tried a bunch of tools online and none has been able to parse the CSV file correctly. I am baffled by the fact that i am in here asking for help as one would think parsing CSV data would be something super easy.
The format of the CSV data is like this:
",95,54070,3635,""Test Reservation"",0,102,0.00,0.00,2014-12-31,""Name of customer"",""$12.34 + $10, special price"",""extra information"",,CustomerName,,,,,1234567890,youremail#domain.com,CustomerName,2014-12-31,23:59:59,16,0,60,2,120,0,NULL,NULL,NULL,"
Current code:
private void btnOpenFileDialog_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
ParseCsvLine(line);
}
}
}
}
private void ParseCsvLine(string line)
{
if (line != string.Empty)
{
string[] result;
using (var csvParser = new TextFieldParser(new StringReader(line)))
{
csvParser.Delimiters = new string[] { "," };
result = csvParser.ReadFields();
}
foreach (var item in result)
{
Console.WriteLine(item + Environment.NewLine);
}
}
}
The result variable only has one item and its:
,95,54070,3635,"Test Reservation",0,102,0.00,0.00,2014-12-31,"Name of customer","$12.34 + $10, special price","extra information",,CustomerName,,,,,1234567890,youremail#domain.com,CustomerName,2014-12-31,23:59:59,16,0,60,2,120,0,NULL,NULL,NULL,
// Add Microsoft.VisualBasic.dll to References.
using Microsoft.VisualBasic.FileIO;
// input is your original line from csv.
// Remove starting and ending quotes.
input = input.Remove(0, 1);
input = input.Remove(input.Length - 1);
// Replace double quotes with single quotes.
input = input.Replace("\"\"", "\"");
string[] result;
using (var csvParser = new TextFieldParser(new StringReader(input)))
{
csvParser.Delimiters = new string[] { "," };
result = csvParser.ReadFields();
}
You can check out a previous post that deals with those pesky commas in csv files. I'm linking it here.
Also Mihai, your solution works well for just the one line but will fail once there are many lines to parse.

Can I programatically copy my html selection

I have a html document that after being parsed contains only formatted text.I was wondering if it is possible to get its text like I would do if I was mouse-selecting it + copy + paste in new Text Document?
I know that this is possible in Microsoft.Office.Interop where I have .ActiveSelection property that selects the content of the open Word.
I need to find a way to load the html somehowe(maybe in a browser object) and then copy all of its content and assign it to a string.
var doc = new HtmlAgilityPack.HtmlDocument();
var documetText = File.ReadAllText(myhtmlfile.html, Encoding.GetEncoding(1251));
documetText = this.PerformSomeChangesOverDocument(documetText);
doc.LoadHtml(documetText);
var stringWriter = new StringWriter();
AgilityPackEntities.AgilityPack.ConvertTo(doc.DocumentNode, stringWriter);
stringWriter.Flush();
var titleNode = doc.DocumentNode.SelectNodes("//title");
if (titleNode != null)
{
var titleToBeRemoved = titleNode[0].InnerText;
document.DocumentContent = stringWriter.ToString().Replace(titleToBeRemoved, string.Empty);
}
else
{
document.DocumentContent = stringWriter.ToString();
}
and then I return the document object.The problem is that the string is not always formatted as I want it to be
You should be able to just use StreamReader and as you read each line just write it out using StreamWriter
Something like this will readuntil the end of your file and save it to a new one. If you need to do extra logic in the file I have a comment inserted to let you know where to do all that.
private void button4_Click(object sender, EventArgs e)
{
System.IO.StreamWriter writer = new System.IO.StreamWriter("C:\\XXX\\XXX\\XXX\\test2.html");
String line;
using (System.IO.StreamReader reader = new System.IO.StreamReader("C:\\XXX\\XXX\\XXX\\test.html"))
{
//Do until the end
while ((line = reader.ReadLine()) != null) {
//You can insert extra logic here if you need to omit lines or change them
writer.WriteLine(line);
}
//All done, close the reader
reader.Close();
}
//Flush and close the writer
writer.Flush();
writer.Close();
}
You can also save it to a string then just do whatever you want to with it. You can use new lines to keep the same format.
EDIT The below will tke into account your tags
private void button4_Click(object sender, EventArgs e)
{
String line;
String filetext = null;
int count = 0;
using (System.IO.StreamReader reader = new System.IO.StreamReader("C:\\XXXX\\XXXX\\XXXX\\test.html"))
{
while ((line = reader.ReadLine()) != null) {
if (count == 0) {
//No newline since its start
if (line.StartsWith("<")) {
//skip this it is formatted stuff
}
else {
filetext = filetext + line;
}
}
else {
if (line.StartsWith("<"))
{
//skip this it is formatted stuff
}
else
{
filetext = filetext + "\n" + line;
}
}
count++;
}
Trace.WriteLine(filetext);
reader.Close();
}
}

How to use textfieldParser to edit a CSV file?

I wrote a small function that reads a csv file using textField line by line , edit it a specific field then write it back to a CSV file.
Here is the code :
private void button2_Click(object sender, EventArgs e)
{
String path = #"C:\file.csv";
String dpath = #"C:\file_processed.csv";
List<String> lines = new List<String>();
if (File.Exists(path))
{
using (TextFieldParser parser = new TextFieldParser(path))
{
String line;
parser.HasFieldsEnclosedInQuotes = true;
parser.Delimiters = new string[] { "," };
while ((line = parser.ReadLine()) != null)
{
string[] parts = parser.ReadFields();
if (parts == null)
{
break;
}
if ((parts[12] != "") && (parts[12] != "0"))
{
parts[12] = parts[12].Substring(0, 3);
//MessageBox.Show(parts[12]);
}
lines.Add(line);
}
}
using (StreamWriter writer = new StreamWriter(dpath, false))
{
foreach (String line in lines)
writer.WriteLine(line);
}
MessageBox.Show("CSV file successfully processed ! ");
}
}
The field I want to edit is the 12th one (parts[12]):
for example : if parts[12] = 000,000,234 then change to 000
the file is created the problem is it does not edit the file and half the records are missing. I am hoping someone could point the mistake.
You call both parser.ReadFields() and parser.ReadLine(). Each of them advance the cursor by one. That's why you're missing half the rows. Change the while to:
while(!parser.EndOfData)
Then add parts = parser.ReadFields(); to the end of the loop. Not having this is why you're edit isn't being seen.
You can also remove:
if (parts == null)
{
break;
}
Since you no longer have line, you'll need to use the fields to keep track of your results:
lines.Add(string.Join(",", parts));//handle string escaping fields if needed.

Categories

Resources