I have text file with employes email like this below
abc#ewr.com
xyc#df.co.nz
rte#pope.com
ssddsf#fdf.com
I want change to like this
abc#ewr.com, xyc#df.co.nz, rte#pope.com, ssddsf#fdf.com
How can i do using C# code?
string yourString = oldString.Replace(' ', ',');
Most likely it is not a space but a new line, so it would be
string yourString = oldString.Replace(Environment.NewLine, ",");
Could do this;
string linesFromFile = string.Empty;
// Read into string from file
using (StreamReader sr = new StreamReader("filename.txt"))
{
linesFromFile = sr.ReadToEnd();
linesFromFile = linesFromFile.Replace(Environment.NewLine, ",");
Console.WriteLine(linesFromFile);
}
// Write back from string to file
using (StreamWriter sw = new StreamWriter("newFilename.txt"))
{
foreach(string s in linesFromFile.Split(','))
{
sw.WriteLine(s);
}
}
this would replace CR\LF and spaces with ','
string newContent = string.Join(",",
File.ReadAllLines("sourceFile.txt")
).Replace(' ', ',')
File.WriteAllText("newFile.txt", newContent);
I'd operate on the file directly to avoid the overhead of reading a potentially huge employee database into a string:
private static void MungeFile(string filename)
{
FileStream fsOut = File.Create(filename+"_out");
FileStream fsIn = File.OpenRead(filename);
StreamReader sr = new StreamReader(fsIn);
StreamWriter sw = new StreamWriter(fsOut);
while (!sr.EndOfStream)
{
string inputLine = sr.ReadLine();
string terminator = (sr.EndOfStream ? "" : ",");
sw.Write(inputLine + terminator);
}
sw.Flush();
fsOut.Close();
}
Microsoft's documentation covers this one pretty well: http://msdn.microsoft.com/en-us/library/ms228599.aspx
Read in the text file as a string, then do something like this to replace the newlines with a comma (replace Environment.NewLine with ' ' if you are looking to replace spaces):
String newFile = oldFile.Replace(Environment.NewLine,',');
Related
I Have one text file and I want to replaces all matches in each line, so I defined Pattern and I loop through to the text file after I want to write the result in another file, unfortunately my pattern is only replace first occurrence of the word what did |I do in a wrong way?
Content of text file:
"testebook kok o testebook\ntestbbb1232 joj ds testbbb1232"
using System.Text.RegularExpressions;
string filePath = "test.txt";
string fileNewPath = "test1.txt";
string ma = #"^test[0-9a-zA-Z]+";
string newString = string.Empty;
using(StreamReader sr = new(filePath)){
string line = sr.ReadLine();
while (line != null){
while(Regex.IsMatch(line, ma) != false){
line = Regex.Replace(line, ma, "");
}
newString += line + "\n";
line = sr.ReadLine();
}
}
using(StreamWriter sw = new(fileNewPath)){
sw.WriteLine(newString);
}
Your code is correct but your regex pattern is not correct.
you should write this:
string ma = #"test[0-9a-zA-Z]+";
The letter "^" has removed from pattern
So I modified My pattern and remove start with character and everything works now as desired
using System.Text.RegularExpressions;
string filePath = "test.txt";
string fileNewPath = "test1.txt";
MatchesFinder test = new(filePath, fileNewPath);
test.RunTheProcess();
class MatchesFinder{
private string filePath;
private string fileNewPath;
private string ma = #"test[a-zA-Z0-9]+";
public MatchesFinder(string filePath,string fileNewPath){
this.filePath = filePath;
this.fileNewPath = fileNewPath;
}
public void RunTheProcess(){
string newString = string.Empty;
using(StreamReader sr = new(filePath)){
string line = sr.ReadLine();
while (line != null){
while(Regex.IsMatch(line, ma) != false){
line = Regex.Replace(line, ma, string.Empty);
}
newString += line.TrimStart() + "\n";
line = sr.ReadLine();
}
}
using(StreamWriter sw = new(fileNewPath)){
sw.WriteLine(newString);
}
}
}
I think you don´t need to check IsMatch separately, just calling Regex.Replace should yield the same result.
Also, newString += line.TrimStart() + "\n"; means you´re copying all the lines you´ve already checked every time you append a new line. I´d either write directly to the output stream or at least use a StringBuilder if you really want to have the full file in memory for some reason.
Something like this:
using var sw = new StreamWriter(fileNewPath);
using var sr = new StreamReader(filePath);
var line = sr.ReadLine();
while (line != null){
line = Regex.Replace(line, ma, string.Empty);
sw.WriteLine(line.TrimStart());
line = sr.ReadLine();
}
I have searched for this but every solution I've come across involves regex witch is not a solution for me.
My question is simple, I want the streamreader to add a new line everytime it reads the word "ice". Keep in mind that the streamreader is reading the input as 1 line.
My code is as follow:
using (StreamReader sr = new StreamReader(stream))
{
VarrileKeeper.s = sr.ReadToEnd();
//Console.WriteLine(VarrileKeeper.s);
if (VarrileKeeper.s.ToString().Contains("ice"))
{
//insert newline in string
}
sr.Close();
}
It seems that your question is exceedingly simple (or you haven't explained the complexities behind your problem).
I'd rather use System.IO.File and String.Replace to solve your problem:
string filename = "D:\\test.txt";
string output = System.IO.File.ReadAllText(filename).Replace("ice", "ice\n");
System.IO.File.WriteAllText(filename, output);
Hope that helped!
Something with string.Split and string.Join could reach your goal
string temp = File.ReadAllText("yourfilename");
var parts = temp.Split(new string[] {"ice"}, StringSplitOptions.None);
VarrileKeeper.s = string.Join("ice"+ Environment.NewLine, parts);
but remember that this is indiscriminate on the character sequence ice, meaning that also more complex words will be truncated (venice for example.)
try this:
VarrileKeeper.s = string.Join(string.Empty, varrileKeeper.s.Split(' ').Select(x => x == "ice" ? x += Environment.NewLine : x += " "));
Try the following:
using (StreamReader sr = new StreamReader(stream))
{
{
VarrileKeeper.s = sr.ReadToEnd();
//Console.WriteLine(VarrileKeeper.s);
if (VarrileKeeper.s.ToString().Contains("ice"))
{
VarrileKeeper.s = VarrileKeeper.s.Replace("ice", "ice" + System.Environment.NewLine);
}
sr.Close();
}
}
I am trying to get a list of words (below) to be put into an array. I want each word to be in it's own index.
Here is my code that I have so far.
string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();
string[] badWordsLine = line.Split(' ');
int BadWordArrayCount = 0;
foreach (string word in badWordsLine)
{
badWords[BadWordArrayCount] = word;
BadWordArrayCount = BadWordArrayCount + 1;
}
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;
Here is the list of words I want to import.
label
invoice
post
document
postal
calculations
copy
fedex
statement
financial
dhl
usps
8
notification
n
irs
ups
no
delivery
ticket
If someone could give me an example of how to get this to work, that would be a huge help.
Simplified code:
string badWordsFilePath = openFileDialog2.FileName.ToString();
string[] badWords = File.ReadAllLines(badWordsFilePath);
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;
If every word starts on a new line then you do not need to create a for loop. The Split method will convert to an array for you.
string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();
string[] badWords = line.Split('\n');
You are splitting on space, but there is a newline between each word. Split on newline instead:
string[] badWordsLine = line.Split(new string[]{ Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
Then you have to create the array to put the words in:
badWords = new string[badWordsLine.Length];
However, to loop through a string array just to copy the strings to a string array seems pointless. Just assing the string array to the variable. Also, you forgot to close the stream reader, which is best taken care of with a using block:
string badWordsFilePath = openFileDialog2.FileName.ToString();
string line;
using (StreamReader sr = new StreamReader(badWordsFilePath)) {}
line = sr.ReadToEnd();
}
badWords = line.Split(new string[]{ Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;
Maybe try this modification? It allows on splitting on various white spaces.
string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();
string[] badWordsLine = line.Split(new string[] {" ", "\t", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
int BadWordArrayCount = 0;
foreach (string word in badWordsLine)
{
badWords[BadWordArrayCount] = word;
BadWordArrayCount = BadWordArrayCount + 1;
}
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;
Do you have to use a StreamReader? If you do not have to, then this code is clearer (in my opinion).
string text = File.ReadAllText(badWordsFilePath);
string[] words = Regex.Split(text, #"\s+");
If you're 100% certain that each word is on its own line and there are no empty lines, this might be overkill; and the File.ReadAllLines suggestion by #Ulugbek Umirov is simpler.
I'm trying to remove any "new line" characters from each line of text in my log file.
Below is an example entry that I am reading in with a Stream Reader :-
<![LOG[Raising event:
[SMS_CodePage(850), SMS_LocaleID(2057)]
instance of SoftDistProgramStartedEvent
{
AdvertisementId = "000216F6";
ClientID = "GUID:B55C2757-CBAE-468E-B54F-46CAF2ECF68F";
CommandLine = "\"C:\\WINNT\\system32\\cscript.exe\" /nologo Shutdown_Desktops_Overnight.vbs";
DateTime = "20130211080211.784000+000";
MachineName = "DWD*****";
PackageName = "0000073C";
ProcessID = 2516;
ProgramName = "Shutdown Desktops Overnight";
SiteCode = "S00";
ThreadID = 3640;
UserContext = "NT AUTHORITY\\SYSTEM";
WorkingDirectory = "C:\\WINNT\\system32\\CCM\\Cache\\0000073C.1.System\\";
};
]LOG]!><time="08:02:11.800+000" date="02-11-2013" component="execmgr" context="" type="1" thread="3640" file="event.cpp:522">
In the actual Logfile this is displayed as one line in the file, with the "New Line Characters" replaced with a square.
I'm using the following code to read in the log entries :-
using (StreamReader sr = new StreamReader(#"C:\Documents and Settings\riversd\Desktop\Logfile2.log"))
{
string Line;
while ((Line = sr.ReadLine()) != null)
{
}
}
The issue is that when the StreamReader reads this entry from the txt file it breaks at :-
"<![LOG[Raising event:"
I need to remove all new line characters in this entry, on the fly. I don't want to read the entire file into memory and then remove them, I'd rather deal with each log as I read it.
Is it possible?
The call to Replace isn't working because of this detail from the MSDN doc of StreamReader.ReadLine:
A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n"). The string that is returned does not contain the terminating carriage return or line feed.
So if you're going to use StreamReader.ReadLine to read in the input, you could build up a new string with StringBuilder.Append (not AppendLine) as StreamReader.ReadLine implicitly removes the new line characters.
var filePath = "text.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader reader = new StreamReader(filePath))
{
while (!reader.EndOfStream)
{
sb.Append(reader.ReadLine());
}
}
File.WriteAllText(filePath, sb.ToString());
sr.ReadLine().Replace(Environment.NewLine, String.Empty);
EDIT:
In case the end of line is not \r\n but \n you can use regex:
Line = Regex.Replace(sr.ReadLine(), #"(\r\n|\n)", String.Empty);
i dont know if anyone else was having exactly this issue.
here is the code i used to fix this issue.
using (System.IO.FileStream File = new System.IO.FileStream(e.FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
{
using (System.IO.StreamReader Reader = new System.IO.StreamReader(File, Encoding.Default))
{
String CompleteData = Reader.ReadToEnd();
foreach (String Line in CompleteData.Split(new char[] { (char)13 }, StringSplitOptions.RemoveEmptyEntries))
{
if (Line.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)[0].Contains("Raising event"))
{
//Do Stuff
}
}
Reader.Close();
}
File.Close();
}
For some reason i had to do this because just using streamreader would throw an exception saying that the file is in use from another process.
It might help someone else at a later date..
I am making a project that uses streamreader and streamwriter, Is it possible that I only replace or save a text in an specific line only without affecting the other lines?
if I make like this
streamreader sr = new streamreader(#"txtfile");
list<string> lines = new list<string>();
while (!sr.EndOfStream)
sr.readline();
{
lines.Add(sr.ReadLine();
}
//put in textbox
sr.close();
{
streamwriter sw = new streamwriter(#"txtfile");
sw.WriteLine(textBox1.text);
sw.close();
}
this is just a sample, but Is it possible that I use list also un streamwriter?
If you want a one line solution (code golf :) ) you can use
string path = #"C:\Test.txt";
string lineToReplace = "Relpace This Line";
string newLineValue = "I Replaced This Line";
File.WriteAllLines(path, File.ReadAllLines(path).Select(line => line.Equals(lineToReplace) ? newLineValue : line));
You cannot just change a line as such but you can to ReadAllLines, find the line you want to change, change it and write all of it to the file again :
StringBuilder newFile = new StringBuilder();
string temp = "";
string[] file = File.ReadAllLines(#"txtfile");
foreach (string line in file)
{
if (line.Contains("string you want to replace"))
{
temp = line.Replace("string you want to replace", "New String");
newFile.Append(temp + "\r\n");
continue;
}
newFile.Append(line + "\r\n");
}
File.WriteAllText(#"txtfile", newFile.ToString());
Read the file into memory, changing the line(s) you want to change, close the reader, open the file for writing, write the new contents of the file out.