Find and replace with lookup file - c#

I want to find and replace text in a textfile with a lookup file.
Currently i use the following code to replace a single string:
System.IO.StreamReader objReader;
objReader = new System.IO.StreamReader(someTextFile);
string content = objReader.ReadToEnd();
objReader.Close();
content = content.Replace("Text1", "Replacetext1");
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(someTextFile);
objWriter.Write(content);
objWriter.Close();
I want to use a csv file for lookup. The format of this file is:
Text1, Replacedtext1
Text2, Replacedtext2
Text3, Replacedtext3
etc...
Who can me give some tips?
Thanks

OK Here are some tips:
1) use
string [] allLines = System.IO.File.ReadAllLines("yourLookUpFilePathHere");
it will return all lines in a string array. The same you can do with your file in which you want to make the replacements. Now you can loop through the look up file.
2) At each position / line in the array you can use the method:
string [] partsOfLine = allLines[i].Split('hereYourSeparatorAsChar');
3) now if you have fiddled out the first word you can start a second loop to look for matches in the replacement file and there you can use the line from your code:
allLinesOfReplaceFile[i] = allLinesOfReplaceFile[i].Replace("Text1", "Replacetext1");
I hope you get the drift, if it is still unclear then drop me a comment

Related

How can I use C# to search an XML file for specific words?

I'm very new to C# and XML files in general, but currently I have an XML file that still has some html markup in it (&amp, ;quot;, etc.) and I want to read through the XML file and remove all of those so it becomes easily readable. I can open and print the file to the console with no issue, but I'm stumped trying to search for those specific strings and remove them.
One way to do this would be to put all the words you want to remove into an array, and then use the Replace method to replace them with empty strings:
var xmlFilePath = #"c:\temp\original.xml";
var newFilePath = #"c:\temp\modified.xml";
var wordsToRemove = new[] {"&amp", ";quot;"};
// Read existing xml file
var fileContents = File.ReadAllText(xmlFilePath);
// Remove words
foreach (var word in wordsToRemove)
{
fileContents = fileContents.Replace(word, "");
}
// Create new file with words removed
File.WriteAllText(newFilePath, fileContents);
I suppose you are looking for this: https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.htmldecode?view=netcore-3.1
Converts a string that has been HTML-encoded for HTTP transmission into a decoded string.
// Encode the string.
string myEncodedString = HttpUtility.HtmlEncode(myString);
Console.WriteLine($"HTML Encoded string is: {myEncodedString}");
StringWriter myWriter = new StringWriter();
// Decode the encoded string.
HttpUtility.HtmlDecode(myEncodedString, myWriter);
string myDecodedString = myWriter.ToString();
Console.Write($"Decoded string of the above encoded string is: {myDecodedString}");
Your string is html encoded, probably for transmission over network. So there is a built in method to decode it.

C# can't split a string into an array by newline (from StreamReader)

StreamReader login = new StreamReader("C:/Users/Me/Documents/logins.txt");
string ar = login.ReadToEnd();
string[] names = ar.Split("\r\n");
login.Close();
I'm reading from a file a set of logins, exampled as "username,password" then a newline as "usr,pwd" or something else. I want to split the txt file into a set of arrays by splitting at the start of a new line, but "\r\n" doesn't seem to be working, coming up with the error "cannot convert from string to char". I have tried Environment.Newline, but that is not working either, coming with the same error message.
Instead of dealing with a stream just use File.ReadAllLines
string[] names = File.ReadAllLines("C:/Users/Me/Documents/logins.txt");
String.Split needs an array or eiter char or string values to split on. You need to change your code to:
string[] names = ar.Split(new string[]{"\r\n"}, StringSplitOptions.None);
You can read each line individually like so:
using (StreamReader reader = new StreamReader(pathToFile)) {
string line = reader.ReadLine();
}
This may be preferable as you don't have to rely on the line return type to be correct using a char

How can I replace a line in a text file with a string variable?

using (StreamReader file = new StreamReader(mainMenu.deckFile))
{
while ((line = file.ReadLine()) != null)
{
I am already reading the line that I want to replace, but I don't know how I could replace the line with text stored in a variable. Help is appreciated. Thanks!
You can't "replace" a line in a text file. You have to read the entire text file into a collection in your code, replace the line with your new value, then write the text file back out in its entirety.
string[] lines = File.ReadAllLines(filePath);
// find and replace the line you want.
File.WriteAllLines(filePath, lines);
Read the contents of the file to a string variable or other suitable variable.
If you write the file contents to a string var, use mystringvar.indexof(myline) to see if the line exists then use mystringvar.replace(myline, mynewline) to replace the old line with a new one.
Then update the text file with mystringvar

C# Reading Text File between two unique Chars

my text file looks like the following
things
stuff
more stuff
//xxxxxxxxxxx
these
are the lines
I want to read
into a string
//yyyyyyyyyy
How can I read the lines between "//xxxxxxxxxxx" and "//yyyyyyyyyy"
into a string? also, I will not know what line number it is on; it will change from file to file, as well as how many lines are between those 2 delimiters.
I've figured out how to read the whole file, or how to read certain lines, but not how to just capture a block such as this. I do not want to read the entire file into a string first if that can be avoided. I only want to read the lines between the 2 token into a string.
Did you try the following:
Read each line using String s = StringReader.ReadLine().
If s is not equal to the start read-block token ("//xxxxxxxxxxx"), then ignore it.
Otherwise, start a while loop, and keep reading each line until you see a line that equals your end read-block token ("//yyyyyyyyyy"), and save each line you read into a StringBuilder or just a String.
Here's the code:
string start_token = "//xxxxxxxxxxx";
string end_token = "//yyyyyyyyyy";
String line;
String text = [your text here];
StringReader reader = new StringReader(text);
while (!(line = reader.ReadLine()).Equals(start_token))
{
//ignore
}
String result = "";
while (!(line = reader.ReadLine()).Equals(end_token))
{
result += line;
}
Console.WriteLine(result);

How can I replace my txt file with an array?

I made a array out of a txt file and now i want to replace the array in this txt file (replace like in update).
becouse i edited the array, and now i want to replace the txt file again , i hope its possible and i hope its possible with breaklines.
string[] linesa = File.ReadLines("file1.txt").ToArray();
this is the line where i make a array of my txt.
number = Array.IndexOf(linesa, commonElement);
number = number + 1;
email = linesa[number];
linesa[number] = "";
number = number - 1;
linesa[number] = "";
this is the edit i made and now i want to put it back in the txt file this is where i have alot of problems with.
Just use WriteAllLines method. It will replace the contents of the file if the file exists.
File.WriteAllLines("file1.txt", linesa);

Categories

Resources