I am using StreamWriter to write to a file. When I use a text with 10-50 word text, it works properly. However when i call the function again (it exceeds the 50 words) it crashes. Why is this happening? Any suggestions?
Here is the codes:
StreamWriter file = new StreamWriter("text6.txt");
file.Close();
int count = 0;
string temp = "";
string temp2 = "";
for (Match m = Regex.Match(str, qmatch2); m.Success; m = m.NextMatch())
{
temp = m.Value;
temp2 = Regex.Replace(temp, qmatch2, " . ");
str = Regex.Replace(str, temp, temp2);
}
if (temp.Contains(".") == false)
{
file = File.AppendText("text6.txt");
file.WriteLine(" " + temp);
count++;
file.Close();
}
Try this instead. You only need to create your StreamWriter immediately before you use it, and wrapping it in a using block will ensure that the stream is disposed immediately after you're done using it.
int count = 0;
string temp = "";
string temp2 = "";
for (Match m = Regex.Match(str, qmatch2); m.Success; m = m.NextMatch())
{
temp = m.Value;
temp2 = Regex.Replace(temp, qmatch2, " . ");
str = Regex.Replace(str, temp, temp2);
}
if (temp.Contains(".") == false)
{
using (var file = new StreamWriter("text6.txt"))
{
file.Write("text6.txt");
file.WriteLine(" " + temp);
}
count++;
}
Try this:
StreamWriter file;
try
{
file = new StreamWriter("text6.txt");
file.Close();
}
catch(Exception)
{
throw;
}
Related
Hello I need to find a word in my Richtextbox I need to find the string "ERP Points and ERP Bonus Point"
Here's the contents of a Richboxtext:
https://pastebin.com/vdPQx5E4
Now here's my code:
string resultString = "";
foreach (string line in richTextBox2.Lines)
{
if (line.Contains("ERP Points") || line.Contains("ERP Bonus Point"))
{
resultString = richTextBox2.GetLineFromCharIndex(richTextBox2.Find("ERP", RichTextBoxFinds.MatchCase)).ToString();
var result = Regex.Replace(line, #"\D", "");
string output = Regex.Replace(line, "[^0-9]+", string.Empty);
MessageBox.Show(resultString);
MessageBox.Show(output);
FontArial = 1;
FontSize = Int32.Parse(output);
}
else
{
FontArial = 0;
FontSize = 0;
}
}
and here's my another version which gives me 153 and I don't know where the program gets that:
resultString = richTextBox2.GetLineFromCharIndex(richTextBox2.Find("ERP", RichTextBoxFinds.None)).ToString();
var result = Regex.Replace(line, #"\D", "");
string output = Regex.Replace(resultString, "[^0-9]+", string.Empty);
MessageBox.Show(resultString.ToString());
MessageBox.Show(output);
if (output != "")
{
FontArial = 1;
FontSize = Int32.Parse(output);
}
else
{
FontArial = 0;
FontSize = 0;
}
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?
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);
currently have the following code:
string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");
for (int i = 0; i < fileLineString.Length; i++)
{
string[] userPasswordPair = fileLineString[i].Split(' ');
if (Session["user"].ToString() == userPasswordPair[0])
{
userPasswordPair[i].Replace(userPasswordPair[1], newPasswordTextBox.Text);
}
}
}
the text file is set out as: 'username' 'password
what i'm trying to do is be able to edit the password and replace it with a new one using my code, but my code seems to do nothing and the text file just stays the same.
string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");
for (int i = 0; i < fileLineString.Length; i++)
{
string[] userPasswordPair = fileLineString[i].Split(' ');
if (Session["user"].ToString() == userPasswordPair[0])
{
// set the new password in the same list and save the file
fileLineString[i] = Session["user"].ToString() + " " + newPasswordTextBox.Text;
File.WriteAllLines((Server.MapPath("~") + "/App_Data/Users.txt"), fileLineString);
break; // exit from the for loop
}
}
At the moment, you're not storing the file.
Your replace is not assigned to a variable (Replace does not edit or write anything, it just returns the new string object).
Corrected code:
string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");
for (int i = 0; i < fileLineString.Length; i++)
{
string[] userPasswordPair = fileLineString[i].Split(' ');
if (Session["user"].ToString() == userPasswordPair[0])
{
fileLineString[i] = fileLineString[i].Replace(userPasswordPair[1], newPasswordTextBox.Text);
break;
}
}
File.WriteAllLines((Server.MapPath("~") + "/App_Data/Users.txt", fileLineString);
String _userName = "User";
String _newPassword = "Password";
// Reading All line from file
String _fileContent = System.IO.File.ReadAllLines("filePath").ToString();
// Pattern which user password like to changed
string _regPettern = String.Format(#"{0} ?(?<pwd>\w+)[\s\S]*?", _userName);
Regex _regex2 = new Regex(_regPettern, RegexOptions.IgnoreCase);
String _outPut = Regex.Replace(_fileContent, _regPettern, m => m.Groups[1] + " " + _newPassword);
// Writing to file file
System.IO.File.WriteAllText("filePath", _outPut);
I am trying to split the incoming data from a Serial Port, and update text boxes with subsequent data. I first see if a split on '$' is possible, and if the next word after splitting is "GPGGA". If yes, I would like to extract data from this sentence where ',' serves as the separator.
Now, as you see, I update the entire data read by the Serial Port first, and this works fine. The full sentence containing the "GPGGA" line is displayed. But after I split it, the part of the sentence that contains the "GPGGA" looks something like this"GPGGA,1\0\0\0\0\0..." when really the sentence that was just updated to the text box before was "GPGGA,160333,,,......". I am absolutely certain that there is a value after GPGGA in the sentence but when i try to look at it in the debug mode, the string 'ser_data', and hence its subsequent substrings all show the same junk. So, the final text box that I want to update inevitably ends up displaying just 1.
Could anyone tell me why this is happening, and how I can correct it. I need it urgently for my thesis work.
Thanks,
Brett
P.S: I've attached the code below.
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] bData = null;
bData = new byte[40];
serialPort.Read(bData, 0, 40);
string ser_data = System.Text.Encoding.GetEncoding("utf-8").GetString(bData);
txtAck.Invoke(new UpdateTextCallback(this.UpdateTextAck), new object[] { ser_data });
string[] str = null;
str = new string[40];
string[] str_ack = null;
str = ser_data.Split('$');
if (str.Length > 1)
{
for (int i = 1; i < str.Length; i++)
{
string temp1 = null;
temp1 = str[i];
if (temp1.StartsWith("GPGGA"))
{
string[] temp2 = null;
temp2 = temp1.Split(',');
StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
if (temp2.Length > 1)
{
string Time_GPS = temp2[1];
txtEasting.Invoke(new UpdateTextCallback(this.UpdateTextEast), new object[] { Time_GPS });
string text = "Time : " + Time_GPS;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 2)
{
string Lat = temp2[2];
txtLatitude.Invoke(new UpdateTextCallback(this.UpdateTextLat), new object[] { Lat });
string text = " Latitude : " + Lat;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 4)
{
string Long = temp2[4];
txtLongitude.Invoke(new UpdateTextCallback(this.UpdateTextLong), new object[] { Long });
string text = " Longitude : " + Long;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 9)
{
string Alt = temp2[9];
txtNorthing.Invoke(new UpdateTextCallback(this.UpdateTextNorth), new object[] { Alt });
string text = " Altitude : " + Alt;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
string Text = "." + '\n';
objWriter.WriteLine(Text);
objWriter.Close();
temp2 = null;
flag_status = 0;
}
temp1 = null;
}
}
str = null;
SerialPort.Read does not necessarily read the number of characters you ask for.
You need to save the return value, which is the number of characters read.
// nBytesRead will be between 0 and 40, depending on how many bytes were waiting.
int nBytesRead = serialPort.Read(bData, 0, 40);
// Only decode the number of bytes actually retrieved.
string ser_data = System.Text.Encoding.GetEncoding("utf-8").GetString(bData, 0, nBytesRead);
Fixed and majorly cleaned up. This assumes two things: that your encoding is really UTF-8, and that your lines end with newline characters.
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
serialPort.Encoding = ASCIIEncoding.UTF8;
string ser_data = serialPort.ReadLine();
txtAck.Invoke(new UpdateTextCallback(this.UpdateTextAck), new object[] { ser_data });
string[] str = ser_data.Split(new char[] { '$' }, 2);
if (str.Length > 1)
{
for (int i = 1; i < str.Length; i++)
{
string temp1 = str[i];
if (temp1.StartsWith("GPGGA"))
{
StreamWriter objWriter = new StreamWriter(#"D:\Server.txt", true);
try
{
string[] temp2 = temp1.Split(',');
if (temp2.Length > 1)
{
string Time_GPS = temp2[1];
txtEasting.Invoke(new UpdateTextCallback(this.UpdateTextEast), new object[] { Time_GPS });
string text = "Time : " + Time_GPS;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 2)
{
string Lat = temp2[2];
txtLatitude.Invoke(new UpdateTextCallback(this.UpdateTextLat), new object[] { Lat });
string text = " Latitude : " + Lat;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 4)
{
string Long = temp2[4];
txtLongitude.Invoke(new UpdateTextCallback(this.UpdateTextLong), new object[] { Long });
string text = " Longitude : " + Long;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 9)
{
string Alt = temp2[9];
txtNorthing.Invoke(new UpdateTextCallback(this.UpdateTextNorth), new object[] { Alt });
string text = " Altitude : " + Alt;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
objWriter.WriteLine(".\n");
}
finally
{
objWriter.Close();
}
flag_status = 0;
}
}
}
}