For some reason my Else statement is always being executed even when the if statement is.
string line;
string[] columns = null;
while ((line = sr.ReadLine()) != null)
{
columns = line.Split(',');
if (columns.Contains(tboxName.Text))
{
rtBoxResults.Text = ((columns[0] + " " + columns[1] + " " + columns[2] + " " + columns[3]));
}
else
{
MessageBox.Show("No Hotels Found.");
break;
}
Is this because it is searching through every line in the file because of the while loop and not every line contains tboxName?
If so how would it be able to return all values of column[0] without using a while loop?
If I understand correctly, you want to show the message box if none of the lines in the file contain tboxName.Text? If so you can do this check after the while loop completes, using a bool to track whether any line did have a match:
string line;
string[] columns = null;
bool foundHotels = false;
while ((line = sr.ReadLine()) != null)
{
columns = line.Split(',');
if (columns.Contains(tboxName.Text))
{
rtBoxResults.Text = ((columns[0] + " " + columns[1] + " " + columns[2] + " " + columns[3]));
foundHotels = true;
}
}
if(!foundHotels)
{
MessageBox.Show("No Hotels Found.");
}
Try something like this
string[] columns = null;
var isHotels = false;
while ((line = sr.ReadLine()) != null)
{
columns = line.Split(',');
if (columns.Contains(tboxName.Text))
{
rtBoxResults.Text = ((columns[0] + " " + columns[1] + " " + columns[2] + " " + columns[3]));
isHotels = true;
}
} // while loop ends
if (!isHotels)
{
MessageBox.Show("No Hotels Found.");
break;
}
Related
Example .txt file output will be:
lastname|firstname|tintin|password|Manager
lastname|firstname|carley|password|Manager
If I try to register username 'tintin' and other data, it debugs it and says that the username already exists.
If I try to register username 'carley' and other data, the data is recorded in the .txt file even though there is already an existent carley username in the file. Please help.
private void btnregister2_Click(object sender, EventArgs e)
{
FileStream fStream = new FileStream("UserAccount.txt", FileMode.Open);
StreamReader fReader = new StreamReader(fStream);
string fLine = fReader.ReadLine();
string[] fContent = fLine.Split('|');
if (fContent[2].Equals(txtusername2.Text))
{
fContent = fLine.Split('|');
MessageBox.Show("username already exists!");
fLine = fReader.ReadLine();
fReader.Close();
fStream.Close();
}
else
{
fReader.Close();
fStream.Close();
if (string.IsNullOrEmpty(txtlastname.Text) || string.IsNullOrEmpty(txtfirstname.Text) || string.IsNullOrEmpty(txtusername2.Text) || string.IsNullOrEmpty(txtpassword2.Text) || string.IsNullOrEmpty(cmbaccounttype.Text))
{
MessageBox.Show("ERROR! There is an empty text.");
}
else
{
using (StreamWriter record = new StreamWriter("UserAccount.Txt", true))
{
record.WriteLine(txtlastname.Text + "|" + txtfirstname.Text + "|" + txtusername2.Text + "|" + txtpassword2.Text + "|" + cmbaccounttype.Text);
}
MessageBox.Show("Account successfully registered!");
cleanup();
}
}
}
I tried changing the format of my streamwriter, i'm not sure if that's the problem. I'm expecting that there would be no duplicate in the data of the .txt file and what the user inputs.
You only read the first line of the file and you have to read and compare all the lines using while ((s = sr.ReadLine()) != null):
bool _isUserExist = false;
using (StreamReader sr = File.OpenText("UserAccount.txt"))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
if (s.Split('|')[2] == txtusername2.Text)
{
_isUserExist = true;
MessageBox.Show("username already exists!");
break;
}
}
}
if(!_isUserExist)
{
if (string.IsNullOrEmpty(txtlastname.Text) || string.IsNullOrEmpty(txtfirstname.Text) || string.IsNullOrEmpty(txtusername2.Text) || string.IsNullOrEmpty(txtpassword2.Text) || string.IsNullOrEmpty(cmbaccounttype.Text))
{
MessageBox.Show("ERROR! There is an empty text.");
}
else
{
using (StreamWriter record = new StreamWriter("UserAccount.Txt", true))
{
record.WriteLine(txtlastname.Text + "|" + txtfirstname.Text + "|" + txtusername2.Text + "|" + txtpassword2.Text + "|" + cmbaccounttype.Text);
}
MessageBox.Show("Account successfully registered!");
cleanup();
}
}
I have an requirement to read the SGML file and replace if the symbol like comma(,) or full stop (.) then I need to change the symbols and save with the same SGML file itself but I am facing the format issue after replacing the content.
Below is my code and my final output would be store with the same .sgm format.
The below code is working but after replacing the values the output format is differs. Can you suggest for this scenario
Main method:
string resultValue = HTMLToEntity(ReplaceSGML(sbContent.ToString()));
StringReader sr = new StringReader(resultValue.ToString());
SgmlReader reader = new SgmlReader();
reader.WhitespaceHandling = WhitespaceHandling.All;
reader.CaseFolding = Sgml.CaseFolding.ToLower;
reader.InputStream = sr;
StringWriter sw = new StringWriter();
XmlTextWriter w = new XmlTextWriter(sw);
w.Formatting = System.Xml.Formatting.Indented;
w.WriteStartDocument();
reader.Read();
while (!reader.EOF)
{
w.WriteNode(reader, true);
}
//File.WriteAllText(#"C:\Output\test.sgm", );
w.Flush();
w.Close();
Method : ReplaceSGML
private static string ReplaceSGML(string html)
{
XmlDocument xml = new XmlDocument();
xml.Load(_xmlEnglishPath);
XmlNodeList resources = xml.SelectNodes("root/data");
_htmlEnglishDictonaries = new Dictionary<string, string>();
_htmlEnglishDictonaries.Add(";", "{After1Space}"); // replacing semicolon into {After1space}
_htmlEnglishDictonaries.Add(":", "{Before1Space}"); // replacing colon into {Before1Space}
_htmlEnglishDictonaries.Add(".", "{Before1Space}"); // replacing . into {Before1Space}
string line = string.Empty;
StringReader reader = new StringReader(html);
while (reader.Peek() > -1)
{
line = reader.ReadLine();
foreach (var events in _htmlEnglishDictonaries)
{
if (line.Contains(events.Key))
{
// Rule should be implement
// <!-- Replacetext 1.{After1Space}, 2.{Before1Space}, 3.{NoSpace}, 4. {After1LetterCaps} -->
int idx;
if (events.Value.ToLower().Trim() == "{after1space}")
{
idx = line.IndexOf(events.Key) + events.Key.Length;
if (line[idx].ToString() != " ")
{
line = line.Replace(events.Key, events.Key + " ");
}
}
if (events.Value.ToLower().Trim() == "{before1space}")
{
idx = line.IndexOf(events.Key);
if (line[idx].ToString() != " ")
{
line = line.Replace(events.Key, " " + events.Key);
}
}
if (events.Value.ToLower().Trim() == "{before1space},{after1space}")
{
idx = line.IndexOf(events.Key);
if (line[idx].ToString() != " ")
{
line = line.Replace(events.Key, " " + events.Key + " ");
}
}
if (events.Value.ToLower().Trim() == "{nospace}")
{
idx = line.IndexOf(events.Key);
if (line[idx].ToString() != " ")
{
line = line.Replace(events.Key, " " + events.Key);
}
}
if (events.Value.ToLower().Trim() == "{after1lettercaps}")
{
idx = line.IndexOf(events.Key) + events.Key.Length;
if (line[idx].ToString() != " ")
{
if (line[idx + 1].ToString() != " ")
{
line = line.Replace(events.Key, " " + events.Key + line[idx + 1].ToString().ToUpper());
}
else
{
line = line.Replace(events.Key, " " + events.Key);
}
}
}
}
}
}
return line.ToString();
}
Thanks in advance
I don't have much experience with C# but I am trying to make a simple windows forms app with personal finances.
So, I have 2 dataReader (I am using the Oracle provider), and the sql (oracle table) commands that select only 2 columns from a table, only with 1 value, mainly income 1 and income2 and the sum of all values from a specific month.
the sql strings look like this:
strSQL_sel_income1 = "select DISTINCT categorie,SUM(suma) from financiar where main_categ='income' and categorie IN ('income1') and EXTRACT(month FROM data)=" + luna_income + " Group by categorie";
strSQL_sel_income2 = "select DISTINCT categorie,SUM(suma) from financiar where main_categ='income' and categorie IN ('Income2') and EXTRACT(month FROM data)=" + luna_income + " Group by categorie";
the "luna_income" value is taken from a combobox where I select a specific month.
The problem is when I try to declare an Int variable from the values I get with data reader and these variables are not kept outside the while statement... dr_income1/2 being the dataReader
if (dr_income1.HasRows)
{
while (dr_income1.Read())
{
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
int suma_income1 = dr_incomei1.GetInt32(1);
}
}
else
{
label26.Text = "No info;
}
so, I have two similar data readers and two int variables suma_income1 and suma_income2. If I try to make a sum of them, outside the WhIle codes, I get a zero value. Where should I declare the two variables and how to keep their values?
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "Income total: " + suma_income_total;
The suma_income_total is ZERO!!!
dr_income1 = cm1.ExecuteReader();
dr_income2 = cm2.ExecuteReader();
label26.Text = "";
label28.Text = "";
if (dr_income1.HasRows)
{
while (dr_income1.Read())
{
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
int suma_income1 = dr_income1.GetInt32(1);
}
}
else
{
label26.Text = "No info";
}
if (dr_income2.HasRows)
{
while (dr_income2.Read())
{
label28.Text = dr_income2.GetString(0) + ": " + dr_income2.GetInt32(1) + "\n";
int suma_income2 = dr_income2.GetInt32(1);
}
}
else
{
label28.Text = "no info";
}
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "income total: " + suma_income_total;
dr_income2.Close();
dr_income1.Close();
I put some changes in your code. It is not ideal since there are several much simple ways. But it is ok as workaround:
dr_income1 = cm1.ExecuteReader();
dr_income2 = cm2.ExecuteReader();
label26.Text = "";
label28.Text = "";
var suma_income1 =0;
var suma_income2 =0;
if (dr_income1.HasRows)
{
while (dr_income1.Read())
{
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
suma_income1 += dr_income1.GetInt32(1);
}
}
else
{
label26.Text = "No info";
}
if (dr_income2.HasRows)
{
while (dr_income2.Read())
{
label28.Text = dr_income2.GetString(0) + ": " + dr_income2.GetInt32(1) + "\n";
suma_income2 += dr_income2.GetInt32(1);
}
}
else
{
label28.Text = "no info";
}
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "income total: " + suma_income_total;
dr_income2.Close();
dr_income1.Close();
if (GUILayout.Button("Copy settings"))
{
var selection = Selection.gameObjects.ToList();
for (int i = selection.Count - 1; i >= 0; --i)
{
var selected = selection[i];
WriteDataToFile("Transform " + i.ToString() + " Name ==> " + selected.name);
WriteDataToFile("************************" +
"********************");
if (selected.transform.parent != null)
WriteDataToFile(selected.transform.parent.ToString());
WriteDataToFile("local position " + selected.transform.localPosition.ToString());
WriteDataToFile("local rotation " + selected.transform.localRotation.ToString());
WriteDataToFile("local scale " + selected.transform.localScale.ToString());
WriteDataToFile("************************" +
"********************");
WriteDataToFile(" ");
}
}
And the WriteDataToFile:
private void WriteDataToFile(string line)
{
string path = "Assets/Resources/test.txt";
StreamWriter writer = new StreamWriter(path, true);
writer.WriteLine(line);
writer.Close();
}
First I want to check that if I click more then once on the button and it's the same data: name position rotation scale don't write again.
Second how can I read back the lines of the data and assign them into a object ? Also the name. So a new object will be created in the same name parent if the original was parent position rotation and scale.
This is how I'm reading now:
void ReadString()
{
string path = "Assets/Resources/test.txt";
StreamReader reader = new StreamReader(path);
Debug.Log(reader.ReadToEnd());
reader.Close();
}
To add new data to the file that doesn't already exist:
private void WriteDataToFile(string line)
{
string path = "Assets/Resources/test.txt";
string[] text = new string[];
if(File.Exists(path))
{
text = File.ReadAllLines(path);
if(!text.Contains(line))
File.AppendAllText(path, Line);
}
}
If you are not limited to using a text file for storing and retrieving data then I recommend finding a way to write all this data:
WriteDataToFile("Transform " + i.ToString() + " Name ==> " + selected.name);
WriteDataToFile("************************" +
"********************");
if (selected.transform.parent != null)
WriteDataToFile(selected.transform.parent.ToString());
WriteDataToFile("local position " + selected.transform.localPosition.ToString());
WriteDataToFile("local rotation " + selected.transform.localRotation.ToString());
WriteDataToFile("local scale " + selected.transform.localScale.ToString());
WriteDataToFile("************************" +
"********************");
WriteDataToFile(" ");
in less writes because opening and closing the file could be expensive. Maybe something like this:
var selected = selection[i].transform;
string toWrite = $"{parent}:{localPosition}:{localRotation}:{localScale}";
WriteDataToFile(toWrite);
This would mean retrieval would be simply - (not sure the type)
private gameObject GetObjectFromFile(Path, Id)
{
string[] text = new string[];
if(File.Exists(path))
{
text = File.ReadAllLines(path);
foreach(string s in text)
{
if(s.Split(':')[0] == Id.ToString())
{
text = s.Split(':');
break;
}
}
var Id = Convert.ToInt32(text[0]);
var localPosition = Convert.ToInt32(text[1]);
var localRotation = Convert.ToInt32(text[2]);
var localScale = Convert.ToInt32(text[3]);
return new gameObject(Id, localPosition, localRotation, localScale);
}
I need help here.I don't know how to tell to labels from different stringBuilder to go on different .doc files.In my if() statements in need to tell to write labels from first stringBuilder and in another if() statement should write labels from another stingBuilder in another .doc file. Below is my code:
StringBuilder strBody = new StringBuilder();
StringBuilder strBody1 = new StringBuilder();
strBody.Append(#"<html " +
"xmlns:o='urn:schemas-microsoft-com:office:office' " +
"xmlns:w='urn:schemas-microsoft-com:office:word'" +
"xmlns='http://www.w3.org/TR/REC-html40'>" +
"<head><title>Time</title>");
strBody1.Append(#"<html " +
"xmlns:o='urn:schemas-microsoft-com:office:office' " +
"xmlns:w='urn:schemas-microsoft-com:office:word'" +
"xmlns='http://www.w3.org/TR/REC-html40'>" +
"<head><title>Time</title>");
strBody.Append("<body lang=EN-US style='tab-interval:.5in'>" +
"<p style='color:red; font-size:13px'>" +
Label47.Text +"<br/>" +
Label45.Text +"X "+
Label48.Text +" " +
Label54.Text +"</p>" +
"</div></body></html>").Append(strBody1.ToString());
strBody1.Append("<body lang=EN-US style='tab-interval:.5in'>" +
"<p style='color:red; font-size:13px'>" +
Label12.Text +"<br/>" +
Label11.Text +"X "+
Label13.Text +" " +
Label17.Text +"</p>" +
"</div></body></html>");
if (Session["one"] != null && Session["two"] != null && Session["three"] != null)
{
{
string path = #"c:\Backup\kitchen.doc";
string path2 = #"c:\Backup\bar.doc";
if (!File.Exists(path) && !File.Exists(path2))
{
using (StreamWriter sw = File.CreateText(path))
{
using (StreamWriter sw2 = File.CreateText(path2))
{
if (Label53.Text == "4")
{
sw.WriteLine(strBody);
}
else if (Label53.Text == "1")
{
sw2.WriteLine(strBody);
if (Label44.Text == "4")
{
sw.WriteLine(strBody1);
}
else if (Label44.Text == "1")
{
sw2.WriteLine(strBody1);
}
}
I think there is a missing closing } in your if conditions. The
else if (Label53.Text == "1")
did not have a closing }
Updated if conditions
if (Label53.Text == "4")
{
sw.WriteLine(strBody);
}
else if (Label53.Text == "1")
{
sw2.WriteLine(strBody);
}
if (Label44.Text == "4")
{
sw.WriteLine(strBody1);
}
else if (Label44.Text == "1")
{
sw2.WriteLine(strBody1);
}