My program reads registry key values and combines those values with the installation path. I also read the installation path from the registry.
i.e. String dllInstpath = installPath + rKey which equals to:
C:\Program Files (x86)\NSi\AutoStore Workflow 6\HpOXPdCaptureRes.dll
I then use FileVersionInfo on the string above to get the file information of HpOXPdCaptureRes.dll from it's install path and write all the values to a notepad.
My problem is the TRUE dll name does not have 'Res' in the file name. The registry only has the file name with 'Res' in the file name. What I need to do is read from a text file and find all 'Res' and remove them from the line of text within the notepad file.
So the output should look like this:
Current:
HpOXPdCaptureRes.dll
New:
HpOXPdCapture.dll
I have read online and I see the best way to do this is to use ReadAllLines and WriteAllLines. However I am not sure how to implement the find and replace. I have seen a lot of examples on how to remove spaces, invalid characters, etc., but I haven't been able to find an example for what I need.
Summary:
Read text file
Fine Res in all lines of text and remove
Retain current text file, i.e. remove Res and close file
Any help is greatly appreciated.
Thank you!
You can use File.ReadAllLines and File.WriteAllLines.
Example:
Read all the lines and replace the value you want on each line, then write the lines again
File.WriteAllLines("textFilePath",File.ReadAllLines("textFilePath").Select(line => line.Replace("Res.dll", ".dll")));
Just open the file and read all lines using 'File.ReadAllLines'. Then use Replace to remove the Res:
string[] lines = File.ReadAllLines("yourFileName");
var output = lines.Select(x => x.Replace("Res.dll", ".dll")).ToArray();
To later save them back you can use File.WriteAllLines:
File.WriteAllLines("yourFileName", output);
Read everything from file, replace all occurrences of 'res' and write to file:
String filename = "fileName";
StreamReader sr = new StreamReader(filename);
String content = sr.ReadToEnd();
sr.Close();
StreamWriter sw = new StreamWriter(filename);
sw.Write(content.Replace("res", ""));
sw.Close();
If the string you are replacing is guaranteed to be unique in the string - "res.dll" at the end of the string for instance - then you can use Replace method of the String class to do the replacement:
List<string> lines = File.ReadAllLines(sourceFile);
lines = lines.select(l => l.Replace("res.dll", ".dll").ToList();
Or if case sensitivity is an issue:
lines = lines.Select(l => l.Substring(l.Length - 7).ToLower() == "res.dll" ? l.Substring(0, l.Length - 7) + ".dll" : l).ToList();
For more complex cases you might need to use a regular expression to identify the section of the string to replace. Or you might want to split the string int path and filename, modify the filename and join it back together.
Related
I have a file and I need to find a particular string and replace it with another string. The file is created or submitted to us by an external system. The submitted file has 80 characters per line. If a word in the text file doesn't fit into one line, it is split into 2 lines delimited by = symbol at the end of the first line. In the below example, the SAMPLE STRING is split into 2 lines, SAM= in the first line and PLE STRING in the second line. An example is given below
Line 1 text goes here SAM=
PLE STRING and the other texts of the file.
Now I need to find if SAMPLE STRING exists, and then replace with some other sample string. I wrote the below code in C#, but unable to find the string if it spans over multiple lines. Please help.
string filecontents = System.IO.File.ReadAllText("c:\\mytext.txt");
if(filecontents.Contains("SAMPLE STRING"))
{
filecontents = filecontents.Replace("SAMPLE STRING", "SOME_OTHER_STRING");
}
string filecontents = File.ReadAllText("c:\\mytext.txt");
// rebuild the splitted strings
filecontents = filecontents.Replace("=" + System.Environment.NewLine, "");
// remove line breaks from text
filecontents = filecontents.Replace(System.Environment.NewLine, " ");
// no need to use the Contains check, use a straightforward replacement (it will do nothing if the string is not present)
filecontents = filecontents.Replace("SAMPLE STRING", "SOME_OTHER_STRING");
Once this is done, resplit your text into multiple lines with the same criteria. Since the string that replaces your sample has a different length, if you don't perform the replacement using this approach (or an equivalent one) you will end up with your text splitted into lines of unequal length.
I have a text file with many words separated by ;. It looks like this:
eye;hand;mouth;arms;book
three;head;legs;home
I would like to go through this file and search for the symbol ; and modify the file so that every word is transposed with line break.
Should I read the text file in a string first with,
string path = #"c:\temp\MyTest.txt";
string readText = File.ReadAllText(path);
Then check:
if readText.contains(";");
But I don't know what to do next
string readText = File.ReadAllText(path);
var result = readText.Replace(";", Environment.NewLine);
use
readText.Replace(";",Environment.NewLine)
Did you mean this?
string g = readText.Replace(";", "\n");
I am trying to read a CSV file and stored all the values in the single list.CSV file contains credentials as uid(userid) and pass(password) and separated by','I have successfully read all the lines and write it in the file.but when it writes in the file, it write the value in between " "(double quotes) like as("abcdefgh3 12345678")what i want actually to remove this "" double quotes sign when i write it in to the files.i am pasting my code here:
static void Main(string[] args)
{
var reader = new StreamReader(File.OpenRead(#"C:\Desktop\userid1.csv"));
List<string> listA = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
listA.Add(values[0]);
listA.Add(values[1]);
}
foreach (string a in listA)
{
TextWriter tr = new StreamWriter(#"E:\newfiless",true);
tr.Write(a);
tr.Write(tr.NewLine);
tr.Close();
}
}
and the resulted output is like this:
"uid
pass"
"Martin123
123456789"
"Damian
91644"
but i want in this form:
uid
pass
Martin123
123456789
Damian
91644
Thanking you all in advance.
The original file clearly has quotes, which makes it a CSV file with only one colum and in that column there are two values. Not usual, but it happens.
To actually remove quotes you can use Trim, TrimEnd or TrimStart.
You can remove the quotes while reading, or while writing, in this case it doesn't really matter.
var line = reader.ReadLine().Trim('"');
This will remove the quotes while reading. Note that this assumes the CSV is of this "broken" variant.
tr.WriteLine(a.Trim('"'));
This will handle it on write. This will work even if the file is "correct" CSV having two columns and values in quotes.
Note that you can use WriteLine to add the newline, no need for two Write calls.
Also as others have commented, don't create a TextWriter in the loop for every value, create it once.
using (TextWriter tr = new StreamWriter(#"E:\newfiless"))
{
foreach (string a in listA)
{
tr.WriteLine(a.Trim('"'));
}
}
The using will take care of closing the file and other possible resources even if there is an exception.
I assume that all you need to read the input file, strip out all starting/ending quotation marks, then split by comma and write it all to another file. You can actually accomplish it in a one-liner using SelectMany, which will produce a "flat" collection:
File.WriteAllLines(
#"c:\temp\output.txt",
File
.ReadAllLines(#"c:\temp\input.csv")
.SelectMany(line => line.Trim('"').Split(','))
);
It's not quite clear from your example where quotation marks are located in the file. For a typical .CSV file some comma-separated field might be wrapped in quotation marks to allow commas to be a part of the content. If it's the case, then parsing will be more complex.
You can use
tr.Write(a.Substring(1, line.Length - 2));
Edited
Please use Trim
tr.Write(a.TrimEnd('"').TrimStart('"'));
In my page I will get the ID from link parameters, with that ID I will search the database for the file path, after reading the file and storing its contents I want to put its contents inside my <pre> tag... So I will have a literal in which the text for it will be:
Code.Text = "<pre>" + File Contents in string + "</pre>";
My question is how will I insert the contents there if I need to read the file line by line into an string array, unless I read it all into one string, BUT that will make the text look like one huge line in the page.
Also, is it going to conflict with literal syntax(?) definitions, since for quotes we have to do \" instead of " ...?
If you are working with literal control, you use the StringBiulder And Append properties becouse It let you put any HTML code from code behind.
Something like:
//Declare your String Builder
private StringBuilder stb = new StringBuilder();
And also you could have any proccess when you read the file, and split it by any char like \n
string readFile = //Any Method that you read you file string.
string[] tokens = readFile.Split('\n');
stb.Append("<pre>");
foreach (string s in tokens)
{
stb.Append( s + "<\br>");
}
stb.Append("</pre>");
finally you attach the Stringbuilder value to you Literal
YourLiteral.Text = stb.ToString();
I hope that help, and you won't have the value in one line. And remember the carring return need be in the string file to the split works.
Cheers
If I asked the question "how to read a file into a string" the answer would be obvious. However -- here is the catch with CR/LF preserved.
The problem is, File.ReadAllText strips those characters. StreamReader.ReadToEnd just converted LF into CR for me which led to long investigation where I have bug in pretty obvious code ;-)
So, in short, if I have file containing foo\n\r\nbar I would like to get foo\n\r\nbar (i.e. exactly the same content), not foo bar, foobar, or foo\n\n\nbar. Is there some ready to use way in .Net space?
The outcome should be always single string, containing entire file.
Are you sure that those methods are the culprits that are stripping out your characters?
I tried to write up a quick test; StreamReader.ReadToEnd preserves all newline characters.
string str = "foo\n\r\nbar";
using (Stream ms = new MemoryStream(Encoding.ASCII.GetBytes(str)))
using (StreamReader sr = new StreamReader(ms, Encoding.UTF8))
{
string str2 = sr.ReadToEnd();
Console.WriteLine(string.Join(",", str2.Select(c => ((int)c))));
}
// Output: 102,111,111,10,13,10,98,97,114
// f o o \n \r \n b a r
An identical result is achieved when writing to and reading from a temporary file:
string str = "foo\n\r\nbar";
string temp = Path.GetTempFileName();
File.WriteAllText(temp, str);
string str2 = File.ReadAllText(temp);
Console.WriteLine(string.Join(",", str2.Select(c => ((int)c))));
It appears that your newlines are getting lost elsewhere.
This piece of code will preserve LR and CR
string r = File.ReadAllText(#".\TestData\TR120119.TRX", Encoding.ASCII);
The outcome should be always single string, containing entire file.
It takes two hops. First one is File.ReadAllBytes() to get all the bytes in the file. Which doesn't try to translate anything, you get the raw data in the file so the weirdo line-endings are preserved as-is.
But that's bytes, you asked for a string. So second hop is to apply Encoding.GetString() to convert the bytes to a string. The one thing you have to do is pick the right Encoding class, the one that matches the encoding used by the program that wrote the file. Given that the file is pretty messed up if it contains \n\r\n sequences, and you didn't document anything else about the file, your best bet is to use Encoding.Default. Tweak as necessary.
You can read the contents of a file using File.ReadAllLines, which will return an array of the lines. Then use String.Join to merge the lines together using a separator.
string[] lines = File.ReadAllLines(#"C:\Users\User\file.txt");
string allLines = String.Join("\r\n", lines);
Note that this will lose the precision of the actual line terminator characters. For example, if the lines end in only \n or \r, the resulting string allLines will have replaced them with \r\n line terminators.
There are of course other ways of acheiving this without losing the true EOL terminator, however ReadAllLines is handy in that it can detect many types of text encoding by itself, and it also takes up very few lines of code.
ReadAllText doesn't return carriage returns.
This method opens a file, reads each line of the file, and then adds each line as an element of a string. It then closes the file. A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed.
From MSDN - https://msdn.microsoft.com/en-us/library/ms143368(v=vs.110).aspx
This is similar to the accepted answer, but wanted to be more to the point. sr.ReadToEnd() will read the bytes like is desired:
string myFilePath = #"C:\temp\somefile.txt";
string myEvents = String.Empty;
FileStream fs = new FileStream(myFilePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
myEvents = sr.ReadToEnd();
sr.Close();
fs.Close();
You could even also do those in cascaded using statements. But I wanted to describe how the way you write to that file in the first place will determine how to read the content from the myEvents string, and might really be where the problem lies. I wrote to my file like this:
using System.Reflection;
using System.IO;
private static void RecordEvents(string someEvent)
{
string folderLoc = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!folderLoc.EndsWith(#"\")) folderLoc += #"\";
folderLoc = folderLoc.Replace(#"\\", #"\"); // replace double-slashes with single slashes
string myFilePath = folderLoc + "myEventFile.txt";
if (!File.Exists(myFilePath))
File.Create(myFilePath).Close(); // must .Close() since will conflict with opening FileStream, below
FileStream fs = new FileStream(myFilePath, FileMode.Append);
StreamWriter sr = new StreamWriter(fs);
sr.Write(someEvent + Environment.NewLine);
sr.Close();
fs.Close();
}
Then I could use the code farther above to get the string of the contents. Because I was going further and looking for the individual strings, I put this code after THAT code, up there:
if (myEvents != String.Empty) // we have something
{
// (char)2660 is ♠ -- I could have chosen any delimiter I did not
// expect to find in my text
myEvents = myEvents.Replace(Environment.NewLine, ((char)2660).ToString());
string[] eventArray = myEvents.Split((char)2660);
foreach (string s in eventArray)
{
if (!String.IsNullOrEmpty(s))
// do whatever with the individual strings from your file
}
}
And this worked fine. So I know that myEvents had to have the Environment.NewLine characters preserved because I was able to replace it with (char)2660 and do a .Split() on that string using that character to divide it into the individual segments.