read Text File and Make Changes c# - c#

i want to read a text file that Contains
<CustomerName>#CoustomerName</CoustomerName>
<CustomerAddress>#CustomerAddress</CustomerAddress>
<CustomerMobileNo>#CustomerMobileNo</CustomerMobileNo>
<Payment>#Payment</Payment>
Replace this #CoustomerName with Coustomer Name Passes During Run Time
Till then i use this
string readfile = File.ReadAllText(path);
Regex.Replace(readfile , "#CoustomerName ", objProposar.FirstName);
This works But i need to make changes in Coustomer address, mobile no etc
How can i do this

Why regex, a simple String.Replace will do the job:
string oldText = File.ReadAllText(path);
string newText = oldText.Replace("#CoustomerName", objProposar.FirstName);
// other ...
File.WriteAllText(path, newText);

If your file is XML - use XML way of doing it, like XDocument, otherwise string.Replace is a better option:
string readfile = File.ReadAllText(path);
readfile = readfile.Replace("#CoustomerName", objProposar.FirstName);

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.

Find and replace with lookup file

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

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);

Importing Data from a csv file

I have a csv file.
When I try to read that file using filestream readtoend(), I get inverted commas and \r at many places that breaks my number of rows in each column.
Is there a way to remove inverted commas and \r.
I tried to replace
FileStream obj = new FileStream();
string a = obj.ReadToEnd();
a.Replace("\"","");
a.Replace("\r\"","");
When I visualize a all \r and inverted commas are removed.
But when I read the file again from beginning using ReadLine() they appear again?
First of all, a String is immutable. You might think this is not important for your question, but actualy it's important whenever you are developing.
If I look at your code snippet, I'm pretty sure you have no knowledge of immutable objects so I advice you to make sure you fully understand the concept.
More information regarding immutable objects can be found: http://en.wikipedia.org/wiki/Immutable_object
Basicly, it means one can never modify a string object. Strings will always point to a new object whenever we change the value.
That's why the Replace method returns a value, which's documentation can be found here: https://msdn.microsoft.com/en-us/library/system.string.replace%28v=vs.110%29.aspx and states clearly that it Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
In your example, you aren't using the return value of the Replace function.
Could you show us that the string values are actuably being replaced from your a variable? Because I do not believe this is going to be the case. When you visualize a string, carriage returns (\r) are not visual and replaced by an actual carriage return. If you debug and take alook at the actual string value, you should still see the \n.
Take the following code snippet:
var someString = "Hello / world";
someString.Replace("/", "");
Console.Log(someString);
You might think that the console will show "Hello world". However, on this fiddle you can see that it still logs "Hello / World": https://dotnetfiddle.net/cp59i3
What you have to do to correctly use String.Replace can be seen in this fiddle: https://dotnetfiddle.net/XCGtOu
Basicly, you want to log the return value of the Replace function:
var a = "Some / Value";
var b = a.Replace("/", "");
Console.WriteLine(b);
Also, as mentioned by others in the comment section at ur post, you are not replacing the contents of the file, but the string variable in your memory.
If you want to save the new string, make sure to use the Write method of the FileStream (or any other way to write to a file), an explanation can be found here: How to Find And Replace Text In A File With C#
Apart from all what I have been saying throughout this answer, you should not replace both inverted comma's and carriage returns in a file in most cases, they are there for a reason. Unless you do have a specific reason.
At last I succeeded. Thanks to everybody. Here is the code I did.
FileStream obj = new FileStream();
using(StreamReader csvr = new StreamReader(obj))
{
string a = obj.ReadToEnd();
a = a.Replace("\"","");
a = a.Replace("\r\"","");
obj.Dispose();
}
using(StreamWriter Wr = new StreamWriter(TempPath))
{
Wr.Write(a);
}
using(StreamReader Sr = new StreamReader(Tempath))
{
Sr.ReadLine();
}
I Created a temp path on the system. After this things were easy to enter into database.
Try something like this
StreamReader sReader = new StreamReader("filename");
string a = sReader.ReadToEnd();
a.Replace("\"", "");
a.Replace("\r\"", "");
StringReader reader = new StringReader(a);
string inputLine = "";
while ((inputLine = reader.ReadLine()) != null)
{
}

How change file coding from windows-1251 to utf-8

I have xml file and I need to convert the text that I get from it:
I just start to write code, but I don't know how to realize this:
string text = File.ReadAllText(path);
XDocument documentcode = XDocument.Load(text);
You will have to specify the correct encoding when reading:
string text = File.ReadAllText(path, Encoding.GetEncoding("windows-1251"));
XDocument documentcode = XDocument.Parse(text); // not load.
You probably don't have to do anything special when writing.

Categories

Resources