C# separate the words in a text file - c#

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

Related

Remove specific entire word from a string

I have this text file that contains these 3 lines:
Bob
MikeBob
Mike
How could I remove 'Mike' without removing 'Mike' from 'MikeBob'?
I have tried this:
string text = File.ReadAllText("C:/data.txt");
text = text.Replace("Mike", "");
But it removed all occurrences of Mike.
What should I do?
var text = Regex.Replace(File.ReadAllText("C:/data.txt"), "\bMike\b","");
Pretty easy through regex.
// input string
String str = "Hello.???##.##$ here,#$% my%$^$%^&is***()&% this";
// similar to Matcher.replaceAll
str = Regex.Replace(str,#"[^\w\d\s]","");

Find and Delete Characters in String

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.

How to check text file it contains delimiter at the end or not?if it is there how to remove it?

actually i have text file with columns and rows colsep is "'" and row sep is "/"
and my text file is sfsf'fsfsdf'sdfsdf/dfsdf'sfsf'sfsfs/
if my text file contains "/" at the end of the file how to check and remove it it is there
You can use string.TrimEnd()
string str = File.ReadAllText(path);
str = str.TrimEnd('/');
You can use following code:
string fileString = = File.ReadAllText(your file path);
if(fileString[fileString.Length-1].Equals('/'))
{
//your code here;
}
OR you can use:
if(fileString.EndsWith('/'))
{
//yourcode
}
We can check individual characters in string using their index as we all know that:
string is the sequence of characters
this will solve your problem to check last character in file.

Reading from a file in C# without the newline character

i want to read from a text file in C#. But I want all the lines in the file to be concatenated into one line.
for example if i have in the file as
ABCD
EFGH
I need to read ABCDEFGH as one line.
I can do this by reading one line at a time from the file and concatenating that line to a string in a loop. But are there any faster method to do this?
string.Join(" ", File.ReadAllLines("path"));
Replace " " with "" or any other alternative "line-separator"
Example file:
some line
some other line
and yet another one
With " " as separator:
some line some other line and yet another one
With "" as separator:
some linesome other lineand yet another one
Use this:
using (System.IO.StreamReader myFile = new System.IO.StreamReader("test.txt")) {
string myString = myFile.ReadToEnd().Replace(Environment.NewLine, "");
}
What is a one line for you?
If you want to put the entire content of a file into a string, you could do
string fileContent = File.ReadAllText(#"c:\sometext.txt");
If you want your string without newline characters you could do
fileContent = fileContent.Replace(Environment.NewLine, " ");
string file = File.ReadAllText("text.txt").Replace("\r\n", " ");

How do I save a multi-line textbox as one line to a text file?

Ok guys, I am making a function to save a file. I have come across a problem in that when I save the data from multi-line text boxes it saves x amount of lines as x amount of lines in the text file.
So for example if the user entered:
line one
line two
line three
it would show as:
line one
line two
line three
as I want it to display as:
line one \n line two \n line three \n
The code I have is:
savefile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
savefile.Title = "Save your file";
savefile.FileName = "";
savefile.Filter = "ChemFile (*.cd)|*.cd|All Files|*.*";
if (savefile.ShowDialog() != DialogResult.Cancel)
{
// save the text file information
for (int i = 0; i < noofcrit; i++)
{
cdfile[i] = crittextbs[i].Text;
}
}
// Compile the file
SaveFile = savefile.FileName;
System.IO.File.WriteAllLines(SaveFile, cdfile);
Any ideas how I can save multiline text files as one line? Thanks.
Replace Newline character with #" \n "or" \\n ", using # to ignore any escape char
string s= yourTextBox.Text.Replace(Environment.NewLine, #" \n "));
I think you may need to do something like this. I'm not actually sure what the best way is to show escape characters. Also, I would use a StreamWriter.
string myData = txtMyTextBox.Text.Replace("\r"," \\r ").Replace("\n"," \\n ");
using(System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath))
{
sw.Write(myData);
}
If you get the multi-line strings in a string array, you could just join them into a single line:
string[] multiline = new []{"multi","line","text"};
string singleLine = string.Join(#"\n",multiline);
if it's all a single line, a simple Replace would do the trick,
string singleLine = multiline.Replace("\r",string.Empty).Replace("\n",#"\n");
It's all one line really ;)
Multi-line text boxes depending on platform (Win32 here) will save as:
Line\r\n
Line\r\n
Line\r\n
So you just need to replace \r\n with \n or whatever character replacement you want.

Categories