C# - writing a line to text file after a specific line - c#

I have the following code below and I am trying to ensure that the
line(sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype)) ;
is written out to the text file after the line(sw.WriteLine(errLine));.
At the moment when the file is created the lines are not being written to the file in the right order i.e.
sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype) - this line appears first
sw.WriteLine(errLine) - appears second.
Just wondering could you help.
using (StreamWriter sw = File.AppendText(#"D:\Temp\Final.txt"))
try
{
string evnt = Convert.ToString(eventid);
string test = Convert.ToString(testid);
Queue<string> lines = new Queue<string>();
using (var filereader = new StreamReader(#"D:\Temp\Outlook.txt"))
{
string line;
while ((line = filereader.ReadLine()) != null)
{
if (line.Contains(evnt) && line.Contains(test) && evnt != oldevent)
{
sw.WriteLine("----- ERROR -----");
foreach (var errLine in lines)
sw.WriteLine(errLine);
oldevent = evnt;
sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype);
sw.WriteLine(line);
sw.WriteLine("-----------------");
}
lines.Enqueue(line);
while (lines.Count > 10)
lines.Dequeue();
}
}
}

File is being written from up to bottom. Try taking this line
sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype); out of the for loop, before line: foreach (var errLine in lines)

As above you can do below:
File.WriteAllLines(#"D:\Temp\Final.txt", File.ReadLines(#"D:\Temp\Outlook.txt")
.Select(line => line.Contains("Something to find")
? new String[] {"Some caption", line, "More text"}
: new String[] {line};
)
.SelectMany(line => line));

May be Linq is a solution? Something like that:
var source = File
.ReadLines(#"D:\Temp\Outlook.txt")
.Select(line => {
//TODO: put actual code here
if (line.Contains("Something to find"))
return new String[] {"Some caption", line, "More text"};
else
return new String[] {line};
})
.SelectMany(line => line);
File.WriteAllLines(#"D:\Temp\Final.txt", source);

Related

Split result of WebClient.DownloadString into multiple lines [duplicate]

This question already has answers here:
split a string on newlines in .NET
(17 answers)
Closed 3 years ago.
I am trying to get a line foreach line in a webclient.DownloadString("pastebinsite"); but it says cannot convert type 'char' to 'string', so I add a string[] downloaded = wc.DownloadString(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
that does not work because it says cannot convert type 'string' to 'string[]' I am stuck and cannot find a answer online for this.
I have tried changing types
{
StringBuilder sb = new StringBuilder();
Console.WriteLine("start?");
Console.ReadKey();
string[] lines = File.ReadAllLines(Directory.GetCurrentDirectory() + #"\Lines.txt");
WebClient wc = new WebClient();
int _checked = 0;
int _error = 0;
foreach(string line in lines)
{
++_checked;
//Pastebin text viewer
try
{
if (line.Contains("pastebin"))
{
var arac = line.Split('/');
//ERROR LINE CANNOT CONVERT TYPE 'STRING' TO 'STRING[]' Below
string[] downloaded = wc.DownloadString(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
foreach(string line2 in downloaded)
{
if (line2.Contains(":")
{
//Console.WriteLine(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
Console.WriteLine(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
sb.Append(downloaded);
}
}
}
else
{
//Console.WriteLine("Not valid pastebin link!");
}
Console.Title = "Checked : " + _checked;
}
catch(WebException ex)
{
++_error;
Console.WriteLine("Error: " + _error);
}
}
File.WriteAllText(Directory.GetCurrentDirectory() + #"\Output " + _checked + ".txt", sb.ToString());
Console.Clear();
Console.WriteLine("FINISHED");
Console.ReadKey();
}```
wc.DownloadString(..)
returns a string and not a string[].
you need to split the string in order to get a string[]
possible solution if you need that the string[] will contain lines would be:
var stringResult = wc.DownloadString(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
then one of the following:
var lines = stringResult.Split(new [] { '\r', '\n' });
var lines = Regex.Split(stringResult, "\r\n|\r|\n");
var lines = stringResult.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.None)
and finally
foreach(string line in lines) {...}

How to retrieve data from text file

I have data appended line by line in a text file for all confirmed transaction. I want to add Search functionality, where the user enters their E-mail address and all related transaction details connected to that E-mail must be displayed.
bool writeNextLine = false;
StringBuilder sb = new StringBuilder();
// Read the file and display it line by line.
using (System.IO.StreamReader file = new System.IO.StreamReader("record.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(txt_SearchBooking.Text))
{
// This append the text and a newline into the StringBuilder buffer
sb.AppendLine(line.ToString());
lbl_result.Text += sb.ToString();
}
}
}
but only the line containing Email is displayed other details are not.
Email is located on the last line of every transaction detail.
confirmmsg =
" Transaction # : " + EmployeeIDTextBox.Text + ClientIDTextBox.Text + UniqueIDTextBox.Text + "\r\n"
+ " First Name : " + ClientFirstNameTextBox.Text + "\r\n"
+ " Telephone Number : " + ClientTelephoneNumberTextBox.Text + "\r\n"
+ " Investment : " + investmentamt.ToString("C2") + "\r\n"
+ " Interest : " + (twelvemonthint * 100).ToString() + "%" + "\r\n"
+ " Interest Amount : " + (invesmentcalc(investmentamt, twelvemonthterm, twelvemonthint) - investmentamt).ToString("C2") + "\r\n"
+ " Bonus : " + bonus.ToString("c2") + "\r\n"
+ " Total Returns : " + invesmentcalc(investmentamt, twelvemonthterm, twelvemonthint).ToString("C2") + "\r\n"
+ " E-mail : " + ClientEmailTextBox.Text;
This is the data which is written into the text file.
If you always have 9 lines per transaction, with email being the last line, you could use File.ReadAllLines and a counter.
var lines = File.ReadAllLines("records.txt");
for(int i = 0; i < lines.Length; i++)
{
var line = lines[i];
if(line.Contains(txt_SearchBooking.Text))
{
//Retrieve the previous lines
for(int y = i-8; y <= i; y++)
{
lbl_result.Text += lines[y];
}
}
}

Deleting files inside folder in C#

I am creating application to delete files for more than 15 days in past, I've created a project using the C# language "multithreading" to be able to delete these files, but its only reading the first file with the error
The directory name is invalid
Can anyone help me on this please?
private void process3()
{
//DirectoryInfo info1 = new DirectoryInfo(#"\\10.4.9.202\d\PapyrusRes\appdata\");
DirectoryInfo info1 = new DirectoryInfo(#"\\DXB-RASO-MCH\Users\oalahmad\Dropbox\backup\Backup5\Desktop\New folder2");
// long Size = 0;
//C:\Users\oalahmad\Dropbox\backup\Backup5\Desktop\New folder2
String[] filePaths = (from fls in info1.EnumerateFiles()
where (fls.LastWriteTime.Date < DateTime.Today.AddDays(-15))
select fls.FullName).ToArray();
int i = 0;
if (!File.Exists(logPath3))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(logPath3))
{
sw.WriteLine("Deletion Process History:");
sw.WriteLine(" ");
sw.WriteLine(" ");
}
}
//stopwatch.Start();
try
{
foreach (String f in filePaths)
{
DirectoryInfo info = new DirectoryInfo(f);
int difference = DateTime.Today.Subtract(info.LastWriteTime).Days;
textBox2.BeginInvoke(new Action(() =>
{
textBox2.Text += "Folder Name: " + Path.GetFileName(f) +
"\r\nDate Modified: " + difference +
"\r\n------\r\n";
}));
Thread.Sleep(10);
i++;
Directory.Delete(f, true);
count++;
}
using (StreamWriter sw = File.AppendText(logPath3))
{
sw.WriteLine("Successful at: " + DateTime.Now + " " + count +
" files were deleted");
}
}
catch (Exception ex)
{
// log errors
// Write your content here
using (StreamWriter sw = File.AppendText(logPath3))
{
if (count == 0)
sw.WriteLine("Unsuccessful at: " + DateTime.Now + " Error: " +
ex.Message);
else
sw.WriteLine("Unsuccessful at: " + DateTime.Now + " " + count +
" files were deleted" + " Error: " + ex.Message);
}
}
}

how to increase the size of array or free the memory after each iteration. Error: Index was outside the bounds of the array c#

I read data from a text file which is 27 MB file and contains 10001 rows, I need to handle large data. I perform some kind of processing in each row of data and then write it back to a text file. This is the code I have am using
StreamReader streamReader = System.IO.File.OpenText("D:\\input.txt");
string lineContent = streamReader.ReadLine();
int count = 0;
using (StreamWriter writer = new StreamWriter("D:\\ft1.txt"))
{
do
{
if (lineContent != null)
{
string a = JsonConvert.DeserializeObject(lineContent).ToString();
string b = "[" + a + "]";
List<TweetModel> deserializedUsers = JsonConvert.DeserializeObject<List<TweetModel>>(b);
var CreatedAt = deserializedUsers.Select(user => user.created_at).ToArray();
var Text = deserializedUsers.Where(m => m.text != null).Select(user => new
{
a = Regex.Replace(user.text, #"[^\u0000-\u007F]", string.Empty)
.Replace(#"\/", "/")
.Replace("\\", #"\")
.Replace("\'", "'")
.Replace("\''", "''")
.Replace("\n", " ")
.Replace("\t", " ")
}).ToArray();
var TextWithTimeStamp = Text[0].a + " (timestamp:" + CreatedAt[0] + ")";
writer.WriteLine(TextWithTimeStamp);
}
lineContent = streamReader.ReadLine();
}
while (streamReader.Peek() != -1);
streamReader.Close();
This code helps does well up to 54 iterations as I get 54 lines in the output file. After that it gives error "Index was outside the bounds of the array." at line
var TextWithTimeStamp = Text[0].a + " (timestamp:" + CreatedAt[0] + ")";
I am not very clear about the issue if the maximum capacity of array has been violated, if so how can I increase it or If I can write the individual line encountered in loop through
writer.WriteLine(TextWithTimeStamp);
And clean the storage or something that can solve this issue. I tried using list insead of array , still issue is the same.Please help.
Change this line
var TextWithTimeStamp = Text[0].a + " (timestamp:" + CreatedAt[0] + ")";
to
var TextWithTimeStamp = (Text.Any() ? Text.First().a : string.Empty) +
" (timestamp:" + (CreatedAt.Any() ? CreatedAt.First() : string.Empty) + ")";
As you are creating Text and CreatedAt collection objects, they might be empty (0 total item) based on some scenarios and conditions.
Those cases, Text[0] and CreatedAt[0] will fail. So, before using the first element, check if there are any items in the collection. Linq method Any() is used for that purpose.
Update
If you want to skip the lines that do not contain text, change this lines
var TextWithTimeStamp = Text[0].a + " (timestamp:" + CreatedAt[0] + ")";
writer.WriteLine(TextWithTimeStamp);
to
if (Text.Any())
{
var TextWithTimeStamp = Text.First().a + " (timestamp:" + CreatedAt.First() + ")";
writer.WriteLine(TextWithTimeStamp);
}
Update 2
To include all the stringss from CreatedAt rather than only the first one, you can add all the values in comma separated strings. A general example
var strings = new List<string> { "a", "b", "c" };
var allStrings = string.Join(",", strings); //"a,b,c"

Read the whole line till Carriage Return not Line Feed in C#

Is it possible that I can read the whole line of a text file to the next Carriage Return rather than the Line Feed? Currently, I'm reading lines but it counts a Line Feed (LF) as a new line but I need it to only read a new line when it hits a Carriage Return (CR). Is it possible to store a whole line with all the Line Feeds?
while ((line = file.ReadLine()) != null)
{
StreamWriter newFile = new StreamWriter(destination + "\\" + fileName + "_" + fileNumber.ToString() + fileExtension);
newFile.WriteLine(header);
newFile.WriteLine(line);
int counter = 1;
while (counter < fileLength)
{
line = file.ReadLine();
if (line == null)
break;
newFile.WriteLine(line);
counter++;
}
newFile.Close();
log.WriteLine(DateTime.Now + " " + fileName + "_" + fileNumber.ToString() + fileExtension + " created. Card count: " + counter);
fileNumber++;
}
Thanks!

Categories