i have the following code ..i need to loop through end of the file as per the commented code shown below how i can do it ?
namespace BVParser
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(#"D:\Jaison\JaisonWorking\EmailParse\Sample.BV.application.Mails\Sample.BV.application.Mails\ToTest\Test\SourceAscii.msg", Encoding.Unicode);
string message = sr.ReadToEnd();
StreamWriter sw = new StreamWriter(#"D:\Jaison\JaisonWorking\EmailParse\Sample.BV.application.Mails\Sample.BV.application.Mails\ToTest\Test\DestAsciiOutNewWOEncodingUnicode.txt");
sw.Write(message);
sw.Close();
sr.Close();
// StreamReader srseek = new StreamReader(#"D:\Jaison\JaisonWorking\EmailParse\Sample.BV.application.Mails\Sample.BV.application.Mails\ToTest\Test\DestAsciiOutNewWOEncodingUnicode6.txt");
FileStream fs = new FileStream(#"D:\Jaison\JaisonWorking\EmailParse\Sample.BV.application.Mails\Sample.BV.application.Mails\ToTest\Test\DestAsciiOutNewWOEncodingUnicode6.txt", FileMode.Open, FileAccess.Read);
StreamReader r = new StreamReader(fs);
int index = message.IndexOf("prod-");
//Label2.Text = index.ToString();
Cluster.Text = message.Substring(index + 5, 2);
int indexend = message.IndexOf(" ", index);
int indexdiff = indexend - index;
Servers.Text = message.Substring(index, indexdiff);
// Loops should start here.. checking indexat("EOF")
While ()
{
int exindex = message.IndexOf("Exception:");
int checkspace = exindex;
checkspace--;
if (checkspace == ' ')
{
exindex = message.IndexOf("Exception:", exindex);
}
int trav = exindex;
while (message[trav] != '.') // || message[trav] != ' '
{
trav--;
}
int expdiff = exindex - trav + 9;
Exceptions.Text = message.Substring(trav, expdiff);
int lastdescindex = message.IndexOf('\n', exindex);
int firstdescindex = exindex + 10;
int diffdesc = lastdescindex - firstdescindex;
Desc.Text = message.Substring(firstdescindex, diffdesc);
// } Loop should end here.
fs.Close();
}
}
}
This is an example of something I've done...
StreamReader reader = File.OpenText(filename);
string line = null
while ((line = reader.ReadLine()) != null)
{
// ... your stuff here
}
reader.Close();
reader.Dispose();
I also suggest using a StreamReader.
Since it's IDisposable, You can also construct it with the 'using' statement:
using (var reader = new StreamReader(path))
{
string line = null
while ((line = reader.ReadLine()) != null)
{
// do something
}
}
Related
the below code deleting the particular line like: line no 12
but exactly the need is keep the last 7000 lines and delete the remaining lines from the top of the txt.
string line = null;
int line_number = 0;
int line_to_delete = 12;
using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
while ((line = reader.ReadLine()) != null) {
line_number++;
if (line_number == line_to_delete)
continue;
writer.WriteLine(line);
}
}
}
Something like this maybe?
var tempFile = Path.GetTempFileName();
var linesToKeep = File.ReadLines(fileName);
// if the file is less or equal than 7000, do nothing
if(linesToKeep.Count() > 7000) {
linesToKeep = linesToKeep.Skip(linesToKeep.Count() - 7000);
File.WriteAllLines(tempFile, linesToKeep);
File.Delete(fileName);
File.Move(tempFile, fileName);
}
Of course the 7000 can be substituted by something else like a variable.
Two passes of the file for low memory footprint.
int lines_to_keep = 7_000;
string line = null;
int line_number = 0;
int lines_in_file = 0;
using (StreamReader reader = new StreamReader("C:\\input")) {
while ((line = reader.ReadLine()) != null) {
lines_in_file++;
}
}
int lines_to_discard = lines_in_file - lines_to_keep
using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
while ((line = reader.ReadLine()) != null && line_number < lines_to_discard) {
line_number ++
}
while ((line = reader.ReadLine()) != null) {
writer.WriteLine(line);
}
}
}
This question is a continuation of a past discussion HERE. So now I managed to read every line in my text file and also read the exact string in a certain column. My issue now is that I wish to modify a text value in say Column (4) of the tab-base file with another string value.
For example, the original file is like this:
ID1 25 800 Low
ID2 25 700 Low
ID3 25 600 Low
I want to Change to:
ID1 25 800 High
ID2 25 700 High
ID3 25 600 High
… here is my full code. I appreciate your help.
string route = #"C:\MyFile.txt";
FileStream fileStream2 = new FileStream(route, FileMode.Open);
var m_readFile2 = new StreamReader(fileStream2);
var m_writeFile2 = new StreamWriter(fileStream2);
string[] colArr1 = new string[100];
string[] colArr2 = new string[100];
string[] colArr3 = new string[100];
string[] colArr4 = new string[100];
int arrcount = 1;
while ((line = m_readFile2.ReadLine()) != null)
{
string col1 = "";
string col2 = "";
string col3 = "";
string col4 = "";
col1 = line.Split('\t')[0];
col2 = line.Split('\t')[1];
col3 = line.Split('\t')[2];
col4 = line.Split('\t')[3];
colArr1[arrcount] = col1;
colArr2[arrcount] = col2;
colArr3[arrcount] = col3;
colArr4[arrcount] = col4;
m_writeFile2.WriteLine("Serv" + arrcount + "\t" + "25" + "\t" + "400" + "\t" + "High");
arrcount = arrcount + 1;
KISS
string text = File.ReadAllText(route);
text = text.Replace("Low", "High");
File.WriteAllText(route, text);
I would suggest you split the lines into an array and put a new line back together:
string source = #"D:\MyFile.txt";
string destination = #"D:\MyFile2.txt";
int columnToChange = 3;
string newValueForColumn = "High";
using (FileStream sourceStream = new FileStream(source, FileMode.Open))
{
using (FileStream destinationStream = new FileStream(destination, FileMode.CreateNew))
{
using (StreamReader sourceReader = new StreamReader(sourceStream))
{
using (StreamWriter destinationWriter = new StreamWriter(destinationStream))
{
string oldLine = string.Empty;
while ((oldLine = sourceReader.ReadLine()) != null)
{
string[] values = oldLine.Split('\t');
StringBuilder newLine = new StringBuilder();
if (values.Length > columnToChange)
{
values[columnToChange] = newValueForColumn;
for (int i = 0; i < values.Length; i++)
{
newLine.Append(values[i]);
if (i + 1 < values.Length)
{
newLine.Append('\t');
}
}
}
else
{
newLine.Append(oldLine);
}
destinationWriter.WriteLine(newLine.ToString());
}
}
}
}
}
// File.Delete(source);
File.Move(source, source + ".bak");
File.Move(destination, source);
}
//Works fine Thomas Voß - I've just added a line to ensure that Column Header is
//also not changed
string source = #"D:\MyFile.txt";
string destination = #"D:\MyFile2.txt";
int columnToChange = 3;
string newValueForColumn = "High";
using (FileStream sourceStream = new FileStream(source, FileMode.Open))
{
using (FileStream destinationStream = new FileStream(destination, FileMode.CreateNew))
{
using (StreamReader sourceReader = new StreamReader(sourceStream))
{
using (StreamWriter destinationWriter = new StreamWriter(destinationStream))
{
string oldLine = string.Empty;
while ((oldLine = sourceReader.ReadLine()) != null)
{
string[] values = oldLine.Split('\t');
StringBuilder newLine = new StringBuilder();
if (values.Length > columnToChange)
{
if (values[columnToChange] != "ColumnHeaderName")
{
values[columnToChange] = newValueForColumn;
}
for (int i = 0; i < values.Length; i++)
{
newLine.Append(values[i]);
if (i + 1 < values.Length)
{
newLine.Append('\t');
}
}
}
else
{
newLine.Append(oldLine);
}
destinationWriter.WriteLine(newLine.ToString());
}
}
}
}
}
// File.Delete(source);
File.Move(source, source + ".bak");
File.Move(destination, source);
}
I don't understand why I get this error... Can anyone help me?
private void button1_Click(object sender, EventArgs e, string filePath)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
Filenametext.Text = of.FileName;
//Create an instance for the openbox dialog
//And opens the explorer to select the wanted file.
{
DataRow row;
DataService m_WsData = new DataService();
string XMLFileName = ConfigurationSettings.AppSettings["XMLPath"].ToString() + DateTime.Now.Ticks.ToString() + ".xml";
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding("ISO-8859-1"));
{
DataSet ds = m_WsData.GEDS();
string line = "";
int lineNo = 0;
string lineStart = "";
string lineEnd = "";
string[] fileRow;
{
line = sr.ReadLine();
if (line != null)
{
fileRow = line.Split(new Char[] { ';' });
if (lineNo == 0)
{
lineStart = fileRow[0];
}
if (fileRow[0] != "00" && fileRow[0] != "99")
{
row = ds.Tables["FuelFileData"].NewRow();
row["TransNo"] = fileRow[0];
row["CustomerNo"] = fileRow[1];
row["TruckNo"] = fileRow[2];
row["FuelDate"] = fileRow[3];
row["FuelTime"] = fileRow[4];
row["Place"] = fileRow[5];
row["FuelTypeNo"] = fileRow[6];
row["FuelDescription"] = fileRow[7];
row["DriverNo"] = fileRow[8];
row["Blank"] = fileRow[9];
row["TransType"] = fileRow[10];
row["Fuel"] = fileRow[11];
row["FuelCost"] = fileRow[12];
row["MileageFile"] = fileRow[13];
row["DrivenKm"] = fileRow[14];
row["AverageConsFile"] = fileRow[15];
//row["ImportedGuid"]=fileRow[16];
}
lineEnd = fileRow[0];
lineNo++;
}
} while (line != null);
lineStart = lineStart.Trim() + lineEnd.Trim();
fs.Close();
if (lineStart == "0099")
{
ds.WriteXml(XMLFileName);
System.IO.File.Delete(XMLFileName);
}
}
}
}
Cause
You cannot add parameters on event handler methods.
The Click event is defined as
public event RoutedEventHandler Click;
which means that the handler must match the delegate RoutedEventHandler which is
public delegate void RoutedEventHandler(Object sender, RoutedEventArgs e);
Solution
Remove the string filePath parameter and pass the path via a public property.
I am needing to have the ability to save data from a dataGridView to a .txt and then be able to load the same data back in to the appropriate spots. It is databound.
Here is the code that I have so far.
I can save to file but, it will only load the first record in the file into the dataGridView.
Any help is greatly appreciated!
private void LoadButton_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog().Equals(DialogResult.OK))
{
cardlist = new List<Card>();
using (System.IO.StreamReader file = new System.IO.StreamReader(openFileDialog1.FileName))
{
Card newcard = new Card();
newcard.CardName = file.ReadLine();
newcard.NumBorrowed = Convert.ToInt32(file.ReadLine());
cardlist.Add(newcard);
}
dataGridView1.DataSource = cardlist;
}
}
private void SaveButton_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog().Equals(DialogResult.OK))
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(saveFileDialog1.FileName))
foreach (Card currentCard in cardlist)
{
file.WriteLine(currentCard.CardName);
file.WriteLine(currentCard.NumBorrowed);
}
}
}
public class Card
{
public String CardName { get; set; }
public int NumBorrowed { get; set; }
}
You need to iterate over all items in the file
Replace This:
using (System.IO.StreamReader file = new System.IO.StreamReader(openFileDialog1.FileName))
{
Card newcard = new Card();
newcard.CardName = file.ReadLine();
newcard.NumBorrowed = Convert.ToInt32(file.ReadLine());
cardlist.Add(newcard);
}
With This:
int lineCount=0;
string line=string.Empty;
using (System.IO.StreamReader file = new System.IO.StreamReader(openFileDialog1.FileName))
{
Card newcard = new Card();
while((line=file.ReadLine()) != null)
{
if(lineCount == 0)
{
newcard.CardName = line;
lineCount = 1;
}
else if(lineCount == 1)
{
newcard.NumBorrowed = Convert.ToInt32(line);
lineCount = 0;
}
cardlist.Add(newcard);
}
OR
int i=0;
foreach(var line in File.ReadLines(openFileDialog1.FileName))
{
Card newcard = new Card();
if(i==0)
{
newcard.CardName = line;
i = 1;
}
else if(i==1)
{
newcard.NumBorrowed = Convert.ToInt32(line);
i=0;
}
cardlist.Add(newcard);
}
Try the following code :
using (System.IO.StreamReader file = new System.IO.StreamReader(openFileDialog1.FileName))
{
string line;
while ((line = file.ReadLine()) != null)
{
Card newcard = new Card();
newcard.CardName = line;
newcard.NumBorrowed = Convert.ToInt32(line);
cardlist.Add(newcard);
}
}
This will cause the code to loop through the file until it reaches a null line (i.e. End of file).
This will place the entire line inside both CardName and NumBorrowed.
For this to work correctly you will either need to read 2 lines per loop, like so :
string line;
string line2;
while ((line = file.ReadLine()) != null && (line2 = file.ReadLine()) != null) {
}
And then you can correct your code :
Card newcard = new Card();
newcard.CardName = line;
newcard.NumBorrowed = Convert.ToInt32(line2);
cardlist.Add(newcard);
Alternatively, you could change your file Format and instead of having 2 lines per info, you could condense it onto one line with a seperating value (i.e. Jake^50 where ^ is the seperator)
You then need to just modify the code to split the line into an array and pull the values from that.
If i had my druthers, I'd write my text file delimited with one record per line and then not worry that 1 bad line will mess up all the following lines, but with your current structure this should work and it has a little error checking.
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
bool stillReading = true;
while (stillReading)
{
string card, numBorrowed;
card = reader.ReadLine();
numBorrowed = reader.ReadLine();
if (card != null && numBorrowed != null)
{
int numB;
Card newcard = new Card
{
CardName = card,
NumBorrowed = Int32.TryParse(numBorrowed, out numB) ? numB : 0
};
cardlist.Add(newcard);
}
else
{
stillReading = false;
}
}
}
I'm trying to read my apache log and do some processing with it. I use a string split function which contains log lines which refer to me in so way. I want to remove those lines. The code below shows that I've got. It only removes "127.0.0.1" but all the "192.168.1.x" lines appear.
How do I remove EVERY split string?
public void GetTheLog()
{
string path = "c:\\program files\\Zend\\apache2\\logs\\access.log";
string path2 = #"access.log";
int pos;
bool goodline = true;
string skipIPs = "127.0.0.1;192.168.1.100;192.168.1.101;192.168.1.106;67.240.13.70";
char[] splitchar = { ';' };
string[] wordarray = skipIPs.Split(splitchar);
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader reader = new StreamReader(fs);
TextWriter tw = new StreamWriter(path2);
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
// initialize goodline for each line of reader result
goodline = true;
for (j = 0; j < wordarray.Length; j++)
{
pos = -10;
srch = wordarray[j];
ln = line.Substring(0,srch.Length);
pos = ln.IndexOf(srch);
if (pos >= 0) goodline = false;
}
if (goodline == true)
{
tw.WriteLine(line);
listBox2.Items.Add(line);
}
}
// Clean up
reader.Close();
fs.Close();
listBox1.Items.Add(path2);
tw.Close();
}
var logPath = #"c:\program files\Zend\apache2\logs\access.log";
var skipIPs = "127.0.0.1;192.168.1.100;192.168.1.101;192.168.1.106;67.240.13.70";
var filters = skipIPs.Split(';');
var goodlines = File.ReadLines(logPath)
.Where(line => !filters.Any(f => line.Contains(f)));
Then you can
File.WriteAllLines(#"access.log", goodlines);
And it also looks like you're dumping the lines into a listbox
listBox2.Items.AddRange(goodlines.Select(line=> new ListItem(line)).ToArray());
Also, since your skipIPs are just a static string, you could refactor a little and just do
var filters = new []{"127.0.0.1","192.168.1.100","192.168.1.101",...};
arrrrrr din get what you want...
okh let me try if you want to remove all the IPs which are present in your skipIPs from your current file.
then you can simply use....
if(ln==srch)
{
goodline = false;
}
instead of
pos = ln.IndexOf(srch);
if (pos >= 0) goodline = false;
inside your for loop.
hope it will jelp you... :)