Error , invalid Regular expression in c# console application - c#

private static void PizzaHutPizzaScrapper()
{
try
{
MatchCollection mclName;
MatchCollection mclPrice;
WebClient webClient = new WebClient();
string strUrl = "http://www.pizzahut.com.pk/pizzas.html";
byte[] reqHTML;
reqHTML = webClient.DownloadData(strUrl);
UTF8Encoding objUTF8 = new UTF8Encoding();
string pageContent = objUTF8.GetString(reqHTML);
Regex r = new Regex("(<p class=\"MenuDescHead\">[A-Za-z\\s*]+[0-9]*)");
// Regex r1 = new Regex("(<p class=\"MenuDescPrice\">[A-Za-z.\\s?]+[0-9]*[A-Za-z\\s?]*[0-9]*[A-Za-z.\\s?]*)");
Regex r1 = new Regex("(<p class=\"MenuDescPrice\">[0-9]*)");
mclName = r.Matches(pageContent);
mclPrice = r1.Matches(pageContent);
StringBuilder strBuilder = new StringBuilder();
string name = "";
string price = "";
List<string> menuPriceList = new List<string>();
foreach (Match ml in mclPrice)
{
price = ml.Value.Remove(0, ml.Value.IndexOf(">") + 1).Trim();
if (price != "")
{
menuPriceList.Add(ml.Value);
}
}
int j = 0;
for (int i = 0; i < mclName.Count; i++)
{
name = mclName[i].Value.Remove(0, mclName[i].Value.IndexOf(">") + 1);
if (i == 0 || i == 4)
{
price = menuPriceList[j].Remove(0, menuPriceList[j].IndexOf(">") + 1);
strBuilder.Append(name.Trim() + ", " + price.Trim() + " , PizzaHut\r\n");
j++;
}
price = menuPriceList[j].Remove(0, menuPriceList[j].IndexOf(">") + 1);
strBuilder.Append(name.Trim() + ", " + price.Trim() + " ,PizzaHut\r\n");
j++;
}`
i want to select numeric values only...but it fetch alphabets as well..
i want to select only numeric values from HTML and using [0-9]* as regular expression, but its not working and show alphabets as well. i want only numeric values, what is correct regular expression? any idea??

Here you go, what you're looking for are Grouping Constructs:
MatchCollection mclName;
MatchCollection mclPrice;
WebClient webClient = new WebClient();
string strUrl = "http://www.pizzahut.com.pk/pizzas.html";
byte[] reqHTML;
reqHTML = webClient.DownloadData(strUrl);
UTF8Encoding objUTF8 = new UTF8Encoding();
string pageContent = objUTF8.GetString(reqHTML);
Regex nameRegex = new Regex("<p class=\"MenuDescHead\">([A-Za-z\\s]+[0-9]*)");
Regex priceRegex = new Regex("<p class=\"MenuDescPrice\">[^0-9]*([0-9]*)");
mclName = nameRegex.Matches(pageContent);
mclPrice = priceRegex.Matches(pageContent);
StringBuilder strBuilder = new StringBuilder();
List<string> menuPriceList = new List<string>();
foreach (Match ml in mclPrice)
{
string price = ml.Groups[1].ToString();
if (price != "" && price != "0")
{
menuPriceList.Add(price);
}
}
int j = 0;
for (int i = 0; i < mclName.Count; i++)
{
string price;
string name = mclName[i].Groups[1].ToString();
if (i == 0 || i == 4)
{
price = menuPriceList[j];
strBuilder.Append(name.Trim() + ", " + price.Trim() + " , PizzaHut\r\n");
j++;
}
price = menuPriceList[j];
strBuilder.Append(name.Trim() + ", " + price.Trim() + " ,PizzaHut\r\n");
j++;
}
Console.WriteLine(strBuilder.ToString());

Related

Can I incorporate error handling into my API?

I have an API that loops through addresses and cleanses them. I am testing it with about 40k addresses, and it takes several hours to loop through thousands of them. Sometimes it throws an error and closes out the application and I have to start it over. Is there a way that I can write in error handling into the catch, that if there is an error, it will just log it, but continue running the app?
I am using VS 2019, C#, Windows Forms.
public class Elements
{
public string streetaddress1 { get; set; }
public string streetaddress2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
public string country { get; set; }
}
void Output(string strDebugText)
{
try
{
System.Diagnostics.Debug.Write(strDebugText + Environment.NewLine);
txtResponse.Text = txtResponse.Text + strDebugText + Environment.NewLine;
txtResponse.SelectionStart = txtResponse.TextLength;
txtResponse.ScrollToCaret();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
}
private void btnMultiple_Click(object sender, EventArgs e)
{
//Loads address that need to be cleansed
string filePath = #"C:data.csv";
List<Elements> addresses = new List<Elements>();
List<string> lines = File.ReadAllLines(filePath).ToList();
foreach (var line in lines)
{
string[] entries = line.Split(',');
Elements newElement = new Elements();
newElement.streetaddress1 = entries[0];
newElement.streetaddress2 = entries[1];
newElement.city = entries[2];
newElement.state = entries[3];
newElement.zip = entries[4];
addresses.Add(newElement);
}
foreach (var Element in addresses)
{
Output($"{ Element.streetaddress1 } { Element.city} { Element.state } { Element.zip } " +
$"{ Element.country }");
var venvMulti = new AreaLookup.VertexEnvelope();
var clientMulti = new AreaLookup.LookupTaxAreasWS90Client();
var reqMulti = new AreaLookup.TaxAreaRequestType();
var reqresMulti = new AreaLookup.TaxAreaResultType();
var resMulti = new AreaLookup.TaxAreaResponseType();
string inputXMLMulti;
string outputXMLMulti;
var TALMulti = new AreaLookup.TaxAreaLookupType();
var TALasofDateMulti = new DateTime();
var resTypeMulti = new AreaLookup.TaxAreaLookupResultType();
var postalMulti = new AreaLookup.PostalAddressType();
string StrNoteMulti = "";
int i, y;
var x = default(int);
postalMulti.MainDivision = Element.state;
postalMulti.City = Element.city;
postalMulti.PostalCode = Element.zip;
postalMulti.StreetAddress1 = Element.streetaddress1;
TALasofDateMulti = Conversions.ToDate("2020-12-11");
TALMulti.asOfDate = TALasofDateMulti;
TALMulti.Item = postalMulti;
reqMulti.TaxAreaLookup = TALMulti;
var LITMulti = new AreaLookup.LoginType();
venvMulti.Login = new AreaLookup.LoginType();
venvMulti.Login.UserName = "****";
venvMulti.Login.Password = "****";
venvMulti.Item = reqMulti;
inputXMLMulti = (string)SerializeObjectToString(venvMulti);
Output(inputXMLMulti);
try
{
clientMulti.LookupTaxAreas90(ref venvMulti);
resMulti = (AreaLookup.TaxAreaResponseType)venvMulti.Item;
outputXMLMulti = (string)SerializeObjectToString(venvMulti);
Output(outputXMLMulti);
var loopTo = resMulti.TaxAreaResult.Length - 1;
}
catch (NullReferenceException)
{
Console.WriteLine("Null");
}
reqMulti = default;
reqresMulti = default;
resMulti = default;
void debugOutputCleansedMulti(string strDebugTextCleansedMulti)
{
try
{
System.Diagnostics.Debug.Write(strDebugTextCleansedMulti + Environment.NewLine);
txtCleansed.Text = txtCleansed.Text + strDebugTextCleansedMulti + Environment.NewLine;
txtCleansed.SelectionStart = txtCleansed.TextLength;
txtCleansed.ScrollToCaret();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
}
debugOutputCleansedMulti("Address Cleanse Started: ");
var venvCleansedMulti = new AreaLookup.VertexEnvelope();
var clientCleansedMulti = new AreaLookup.LookupTaxAreasWS90Client();
var reqCleansedMulti = new AreaLookup.TaxAreaRequestType();
var reqresCleansedMulti = new AreaLookup.TaxAreaResultType();
var resCleansedMulti = new AreaLookup.TaxAreaResponseType();
string inputXMLCleansedMulti;
string outputXMLCleansedMulti;
var TALCleansedMulti = new AreaLookup.TaxAreaLookupType();
var TALasofDateCleansedMulti = new DateTime();
var resTypeCleansedMulti = new AreaLookup.TaxAreaLookupResultType();
var postalCleansedMulti = new AreaLookup.PostalAddressType();
string StrNoteCleansedMulti = "";
int a, b;
var c = default(int);
postalCleansedMulti.MainDivision = Element.state;
postalCleansedMulti.City = Element.city;
postalCleansedMulti.PostalCode = Element.zip;
postalCleansedMulti.StreetAddress1 = Element.streetaddress1;
TALasofDateCleansedMulti = Conversions.ToDate("2020-12-11");
TALCleansedMulti.asOfDate = TALasofDateCleansedMulti;
TALCleansedMulti.Item = postalCleansedMulti;
reqCleansedMulti.TaxAreaLookup = TALCleansedMulti;
var LITCleansedMulti = new AreaLookup.LoginType();
venvCleansedMulti.Login = new AreaLookup.LoginType();
venvCleansedMulti.Login.UserName = "****";
venvCleansedMulti.Login.Password = "****";
venvCleansedMulti.Item = reqCleansedMulti;
int j = 1;
//inputXMLCleansed = resCleansed.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + " - " + resCleansed.TaxAreaResult[0].PostalAddress[0].PostalCode + " - " + resCleansed.TaxAreaResult[0].confidenceIndicator;
//debugOutputCleansed(inputXMLCleansed);
try
{
clientCleansedMulti.LookupTaxAreas90(ref venvCleansedMulti);
resCleansedMulti = (AreaLookup.TaxAreaResponseType)venvCleansedMulti.Item;
debugOutputCleansedMulti(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + " | Street Address 1" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2 + " | Street Address 2" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision + " | County" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City + " | City" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode + " | Zip Code" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision + " | State" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].confidenceIndicator + " | Confidence Indicator");
string pathCleansed = #"C:\dev\data\data.csv";
string[] createText = {
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].Country + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision + "," +
resCleansedMulti.TaxAreaResult[0].confidenceIndicator
};
File.AppendAllLines(pathCleansed, createText, System.Text.Encoding.UTF8);
txtCounter.Text = j.ToString();
j++;
var loopTo = resCleansedMulti.TaxAreaResult.Length - 1;
for (b = 0; b <= loopTo; b++)
{
if (c == 0)
{
StrNoteCleansedMulti = resCleansedMulti.TaxAreaResult[b].PostalAddress[0].StreetAddress1 + " - " + resCleansedMulti.TaxAreaResult[b].confidenceIndicator; c = 1;
}
else
{
StrNoteCleansedMulti += ", " + resCleansedMulti.TaxAreaResult[b].taxAreaId + " - " + resMulti.TaxAreaResult[b].confidenceIndicator;
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
reqCleansedMulti = default;
reqresCleansedMulti = default;
resCleansedMulti = default;
}
}
Essentially you need a way to save your work in progress. One pattern would be to load the file and store it in a database, then as you process each line you mark off which item you have processed. If you did this I would split the code into different modules, importing file, processing file, and exporting results.
Another simpler approach might be to write the results out as you process them, and record the line number from the input file. Then if you have to restart, find the last line you output and use that to skip reprocessing the items in your input file

C# Wont save to database after 2nd Click

So my program works as it should. When I click the save button everything is saved to the database. However when I click the save button a second time it fails to work.Index was outside the bounds of the array. is the error in private void btnTest_click on line string Ullage = splitstring[2];
private void btnSave_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\2014-06-26 TEK687 Config Tool\TEK687 Config Tool\bin\Debug\Results.mdb");
string SqlString = "insert into Table1 (PassOrFail,DateTested,TekNum,BatchNum,WeekNum,Serial,FirmwareVer,HardwareVer,TestPC,SettingsTest,Deleted,Ullage,SRC,Vbatt,Tamb,Ullage2,SRC2,Vbatt2,Tamb2) Values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("PassOrFail", txtPassFail.Text);
cmd.Parameters.AddWithValue("DateTested", txtDateTested.Text);
cmd.Parameters.AddWithValue("TekNum", txtTekPartNo.Text);
cmd.Parameters.AddWithValue("BatchNum", txtBatchNumber.Text);
cmd.Parameters.AddWithValue("WeekNum", txtWeekYearNo.Text);
cmd.Parameters.AddWithValue("Serial", txtSerialNumber.Text);
cmd.Parameters.AddWithValue("FirmwareVer", txtFirmwareVer.Text);
cmd.Parameters.AddWithValue("HardwareVer", txtHardwareVer.Text);
cmd.Parameters.AddWithValue("TestPC", txtTestPC.Text);
cmd.Parameters.AddWithValue("SettingsTest", cboSettingsProfiles.SelectedIndex);
cmd.Parameters.AddWithValue("Deleted", txtDeleted.Text);
cmd.Parameters.AddWithValue("Ullage", txtUllage1.Text);
cmd.Parameters.AddWithValue("SRC", txtSRC1.Text);
cmd.Parameters.AddWithValue("Vbatt", txtVbatt1.Text);
cmd.Parameters.AddWithValue("Tamb", txtTamb1.Text);
cmd.Parameters.AddWithValue("Ullage2", txtUllage2.Text);
cmd.Parameters.AddWithValue("SRC2", txtSRC2.Text);
cmd.Parameters.AddWithValue("Vbatt2", txtVbatt2.Text);
cmd.Parameters.AddWithValue("Tamb2", txtTamb2.Text);
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored successfully");
}
ClearTextBoxes(this);
}
Here is the code to add values to database error is at string Ullage = splitstring[2];
private void btnTest_Click(object sender, EventArgs e)
{
Cancel = false;
if (DiscoverDevice(false) == false)
{
MessageBox.Show("Error, device is not responding");
return;
}
string servo = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,S," + txtToolID.Text + ",30,\r\n", "\r\n", 4, ref servo, 500);
string test = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,T," + txtToolID.Text + "\r\n", "\r\n", 4, ref test, 500);
string[] splitstring = test.Split(',');
**string Ullage = splitstring[2];**
string SRC = splitstring[3];
string RSSI = splitstring[4];
string AlarmStatus = splitstring[5];
string RateofChange = splitstring[6];
string Tamb = splitstring[7];
string Vbatt = splitstring[8];
Ullage = Ullage.Replace("u:", "");
Tamb = Tamb.Replace("t:", "");
Vbatt = Vbatt.Replace("v:", "");
int Ull = Convert.ToInt32(Ullage);
int src = Convert.ToInt32(SRC);
int BV = Convert.ToInt32(Vbatt);
int temp = Convert.ToInt32(Tamb);
StringBuilder sb = new StringBuilder();
sb.Append(Ull);
txtUllage1.Text += sb.ToString();
StringBuilder sc = new StringBuilder();
sc.Append(src);
txtSRC1.Text += sc.ToString();
StringBuilder sd = new StringBuilder();
sd.Append(BV);
txtVbatt1.Text += sd.ToString();
StringBuilder se = new StringBuilder();
se.Append(temp);
txtTamb1.Text += se.ToString();
StringBuilder sm = new StringBuilder();
if ((Ull < 11) || (Ull > 13) || (src < 9) || (BV < 29))
{
txtPassFail.Text += "12cm FAIL";
txtResultsReading.Font = new Font(txtResultsReading.Font, FontStyle.Bold);
StringBuilder th = new StringBuilder();
th.Append("12cm FAIL");
txtResultsReading.Text += th.ToString();
}
string servoTwo = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,S," + txtToolID.Text + ",31,\r\n", "\r\n", 4, ref servoTwo, 500);
string tests = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,T," + txtToolID.Text + "\r\n", "\r\n", 4, ref tests, 500);
string[] splitstrings = tests.Split(',');
string Ullage2 = splitstrings[2];
string SRC2 = splitstrings[3];
string RSSI2 = splitstrings[4];
string AlarmStatus2 = splitstrings[5];
string RateofChange2 = splitstrings[6];
string Tamb2 = splitstrings[7];
string Vbatt2 = splitstrings[8];
Ullage2 = Ullage2.Replace("u:", "");
Tamb2 = Tamb2.Replace("t:", "");
Vbatt2 = Vbatt2.Replace("v:", "");
int Ull2 = Convert.ToInt32(Ullage2);
int src2 = Convert.ToInt32(SRC2);
int BV2 = Convert.ToInt32(Vbatt2);
int temp2 = Convert.ToInt32(Tamb2);
StringBuilder sf = new StringBuilder();
sf.Append(Ull2);
txtUllage2.Text += sf.ToString();
StringBuilder sg = new StringBuilder();
sg.Append(src2);
txtSRC2.Text += sg.ToString();
StringBuilder sh = new StringBuilder();
sh.Append(BV2);
txtVbatt2.Text += sh.ToString();
StringBuilder si = new StringBuilder();
si.Append(temp2);
txtTamb2.Text += si.ToString();
txtDateTested.Text = DateTime.Now.ToString();
txtTestPC.Text = System.Environment.UserName;
//boSettingsProfiles.Text= Settings.SettingsFile;
txtDeleted.Text = "CURRENT";
if ((Ull < 11) || (Ull > 13) || (src < 9) || (BV < 29))
{
txtPassFail.Text += " 3M FAIL";
txtResultsReading.Font = new Font(txtResultsReading.Font, FontStyle.Bold);
StringBuilder tg = new StringBuilder();
tg.Append(Environment.NewLine);
tg.Append("3M FAIL");
txtResultsReading.Text += tg.ToString();
}
else if ((Ull >= 11) && (Ull <= 13) && (src == 9) && (BV >= 29) &&
(Ull2 >= 11) && (Ull2 <= 13) && (src2 == 9) && (BV2 >= 29))
{
txtPassFail.Text += "PASS";
txtResultsReading.Font = new Font(txtResultsReading.Font, FontStyle.Bold);
txtResultsReading.Text += "PASS";
}
ReleaseDevice();//release the config tool after config is completed
}
}
Your splitstrings object doesn't have three objects in it, therefore you can't access the object at index 2. Therefore, you should implement a check to make sure it contains an object at that index before accessing, then handle the case where it doesn't as appropriate.
By the way, next time you ask a question about why something doesn't work, it's absolutely critical that you tell us about the exception you're getting, rather than making us ask for it. And you need to include the code that throws the exception. See How to create a Minimal, Complete, and Verifiable example.
Inspect the variable coming out of the WriteTextAndWaitForResponse call. It probably doesn't have 3 commas.

Union of million line urls in 2 files

File A B contains million urls.
1, go through the url in file A one by one.
2, extract subdomain.com (http://subdomain.com/path/file)
3, if subdomain.com exist file B, save it to file C.
Any quickest way to get file C with c#?
Thanks.
when i use readline, it have no much different.
// stat
DateTime start = DateTime.Now;
int totalcount = 0;
int n1;
if (!int.TryParse(num1.Text, out n1))
n1 = 0;
// memory
dZLinklist = new Dictionary<string, string>();
// read file
string fileName = openFileDialog1.FileName; // get file name
textBox1.Text = fileName;
StreamReader sr = new StreamReader(textBox1.Text);
string fullfile = File.ReadAllText(#textBox1.Text);
string[] sArray = fullfile.Split( '\n');
//IEnumerable<string> sArray = tool.GetSplit(fullfile, '\n');
//string sLine = "";
//while (sLine != null)
foreach ( string sLine in sArray)
{
totalcount++;
//sLine = sr.ReadLine();
if (sLine != null)
{
//string reg = "http[s]*://.*?/";
//Regex R = new Regex(reg, RegexOptions.Compiled);
//Match m = R.Match(sLine);
//if(m.Success)
int length = sLine.IndexOf(' ', n1); // default http://
if(length > 0)
{
//string urls = sLine.Substring(0, length);
dZLinklist[sLine.Substring(0,length)] = sLine;
}
}
}
TimeSpan time = DateTime.Now - start;
int count = dZLinklist.Count;
double sec = Math.Round(time.TotalSeconds,2);
label1.Text = "(" + totalcount + ")" + count.ToString() + " / " + sec + " = " + (Math.Round(count / sec,2)).ToString();
sr.Close();
I would go for using Microsoft LogParser for processing big files: MS LogParser. Are you limited to implement it in described way only?

Alternative to ReadLine?

I'm trying to read some files with ReadLine, but my file have some break lines that I need to catch (not all of them), and I don't know how to get them in the same array, neither in any other array with these separators... because... ReadLine reads lines, and break these lines, huh?
I can't replace these because I need to check it after the process, so I need to get the breaklines AND the content after that. That's the problem. How can I do that?
Here's my code:
public class ReadFile
{
string extension;
string filename;
System.IO.StreamReader sr;
public ReadFile(string arquivo, System.IO.StreamReader sr)
{
string ext = Path.GetExtension(arquivo);
sr = new StreamReader(arquivo, System.Text.Encoding.Default);
this.sr = sr;
this.extension = ext;
this.filename = Path.GetFileNameWithoutExtension(arquivo);
if (ext.Equals(".EXP", StringComparison.OrdinalIgnoreCase))
{
ReadEXP(arquivo);
}
else MessageBox.Show("Extensão de arquivo não suportada: "+ext);
}
public void ReadEXP(string arquivo)
{
string line = sr.ReadLine();
string[] words;
string[] Separators = new string[] { "<Segment>", "</Segment>", "<Source>", "</Source>", "<Target>", "</Target>" };
string ID = null;
string Source = null;
string Target = null;
DataBase db = new DataBase();
//db.CreateTable_EXP(filename);
db.CreateTable_EXP();
while ((line = sr.ReadLine()) != null)
{
try
{
if (line.Contains("<Segment>"))
{
ID = "";
words = line.Split(Separators, StringSplitOptions.None);
ID = words[0];
for (int i = 1; i < words.Length; i++ )
ID += words[i];
MessageBox.Show("Segment[" + words.Length + "]: " + ID);
}
if (line.Contains("<Source>"))
{
Source = "";
words = line.Split(Separators, StringSplitOptions.None);
Source = words[0];
for (int i = 1; i < words.Length; i++)
Source += words[i];
MessageBox.Show("Source[" + words.Length + "]: " + Source);
}
if (line.Contains("<Target>"))
{
Target = "";
words = line.Split(Separators, StringSplitOptions.None);
Target = words[0];
for (int i = 1; i < words.Length; i++)
Target += words[i];
MessageBox.Show("Target[" + words.Length + "]: " + Target);
db.PopulateTable_EXP(ID, Source, Target);
MessageBox.Show("ID: " + ID + "\nSource: " + Source + "\nTarget: " + Target);
}
}
catch (IndexOutOfRangeException e)
{
MessageBox.Show(e.Message.ToString());
MessageBox.Show("ID: " + ID + "\nSource: " + Source + "\nTarget: " + Target);
}
}
return;
}
If you are trying to read XML, try using the built in libaries, here is a simple example of loading a section of XML with <TopLevelTag> in it.
var xmlData = XDocument.Load(#"C:\folder\file.xml").Element("TopLevelTag");
if (xmlData == null) throw new Exception("Failed To Load XML");
Here is a tidy way to get content without it throwing an exception if missing from the XML.
var xmlBit = (string)xmlData.Element("SomeSubTag") ?? "";
If you really have to roll your own, then look at examples for CSV parsers,
where ReadBlock can be used to get the raw data including line breaks.
private char[] chunkBuffer = new char[4096];
var fileStream = new System.IO.StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
var chunkLength = fileStream.ReadBlock(chunkBuffer, 0, chunkBuffer.Length);

Problem with file IO streamreader + streamwriter C#

Hi guys I am kinda new to C#. I am trying to do some file io stuff. When I read and write it is only doing it on one line. Is there a way to advance the streamreader/streamwriter? It is for a school assignment. Here is what I have so far. Thanks very much.
enter code her class FileIO
{
public static void Save(ArrayList vehicleList)
{
StreamWriter streamWriter;
FileStream file = new FileStream(Constants.fileName, FileMode.OpenOrCreate);
streamWriter = new StreamWriter(file);
String typeOfVehicle = " ";
String model = " ";
String manufactuer = " ";
Int32 year = 0;
Int32 vin = 0;
Double price = 0;
String purchaseDate = " ";
Int32 currentOdometerReading = 0;
Double sizeOfEngine = 0;
String typeOfMotorCycle = " ";
Int32 numOfDoors = 0;
String typeOfFuel = " ";
Double cargoCapacity = 0;
Double towingCapacity = 0;
foreach (CommonItem vehicle in vehicleList)
{
typeOfVehicle = vehicle.TypeOfVehicle;
model = vehicle.Model;
manufactuer = vehicle.Manufactuer;
year = vehicle.Year;
vin = vehicle.Vin;
price = vehicle.InitialPrice;
purchaseDate = vehicle.PurchaseDate;
currentOdometerReading = vehicle.CurrentOdometerReading;
sizeOfEngine = vehicle.EngineSize;
streamWriter.Write(typeOfVehicle + "~" + manufactuer + "~" + model + "~" + year.ToString() + "~" + vin.ToString() + "~" + price.ToString() + "~" + purchaseDate + "~" + currentOdometerReading.ToString() + "~" + sizeOfEngine.ToString() + "~");
switch (typeOfVehicle)
{
case "Automobile":
numOfDoors = ((Automobile)vehicle).NumberOfDoors;
typeOfFuel = ((Automobile)vehicle).TypeOfFuel;
streamWriter.Write(numOfDoors + "~" + typeOfFuel + "~");
break;
case "Motorcycle":
typeOfMotorCycle = ((Motorcycle)vehicle).Type;
streamWriter.Write(typeOfMotorCycle + "\n");
break;
case "Truck":
cargoCapacity = ((Truck)vehicle).CargoCapacity;
towingCapacity = ((Truck)vehicle).TowingCapacity;
streamWriter.Write(cargoCapacity + "~" + towingCapacity);
break;
}
streamWriter.Write("\n");
}
streamWriter.Close();
}
public static ArrayList Load()
{
ArrayList vehicles = new ArrayList();
FileStream file = new FileStream(Constants.fileName, FileMode.OpenOrCreate);
StreamReader streamReader = new StreamReader(file);
String typeOfVehicle = " ";
String model = " ";
String manufactuer = " ";
Int32 year = 0;
Int32 vin = 0;
Double price = 0;
String purchaseDate = " ";
Int32 currentOdometerReading = 0;
Double sizeOfEngine = 0;
String typeOfMotorCycle = " ";
Int32 numOfDoors = 0;
String typeOfFuel = " ";
Double cargoCapacity = 0;
Double towingCapacity = 0;
String tempString = " ";
while (!String.IsNullOrEmpty(tempString = streamReader.ReadLine()))
{
Int32 temp;
String [] split = tempString.Split('~');
temp = split.Length;
typeOfVehicle = split[0];
manufactuer = split[1];
model = split[2];
year = Convert.ToInt32(split[3]);
vin = Convert.ToInt32(split[4]);
price = Convert.ToDouble(split[5]);
purchaseDate = split[6];
currentOdometerReading = Convert.ToInt32(split[7]);
sizeOfEngine = Convert.ToDouble(split[8]);
if (typeOfVehicle == "Automobile")
{
numOfDoors = Convert.ToInt32(split[9]);
typeOfFuel = split[10];
Automobile car = new Automobile(manufactuer, model, year, vin, price, purchaseDate, currentOdometerReading, sizeOfEngine, numOfDoors, typeOfFuel);
VehicleCount.IncreaseCarCount();
vehicles.Add(car);
}
else if (typeOfVehicle == "Motorcycle")
{
typeOfMotorCycle = split[9];
Motorcycle bike = new Motorcycle(manufactuer, model, year, vin, price, purchaseDate, currentOdometerReading, sizeOfEngine, typeOfMotorCycle);
VehicleCount.IncreaseBikeCount();
vehicles.Add(bike);
}
else
{
cargoCapacity = Convert.ToDouble(split[9]);
towingCapacity = Convert.ToDouble(split[10]);
Truck truck = new Truck(manufactuer, model, year, vin, price, purchaseDate, currentOdometerReading, sizeOfEngine, cargoCapacity, towingCapacity);
VehicleCount.IncreaseTruckCount();
vehicles.Add(truck);
}
}
streamReader.Close();
return vehicles;
}
}
}
When I read and write it is only doing it on one line. Is there a way
to advance the streamreader/streamwriter?
Yes - use streamWriter.WriteLine() instead of streamWriter.Write();
What you are writing looks like data separated by "~" - you might want to look into writing out CSV = comma-separated values, which is similar and pretty much standard.
Also instead of ArrayList you should use a strongly typed collection - in your case depending on your class structure you can use List<Vehicle> (if Automobile and Motorcycle both inherit from Vehicle).
The issue is with this line
while (!String.IsNullOrEmpty(tempString = streamReader.ReadLine()))
The loop exits when it meets a blank line because IsNullOrEmpty method returns true. Try below instead..
while ((tempString = streamReader.ReadLine()) != null)

Categories

Resources