C# regex syntax - c#

My REGEX works here but not in code. I have never done REGEX in C# so I might be missing something syntactically. Any ideas?
Basically I am trying to read through a file old.txt and if a line matches my REGEX then I want to replace it. What I would like to do is read each line, check it with my REGEX (if it doesn't match, fine; if it does, change it) then write THAT line to another file new.txt
As of right now I am writing to the console for testing
static void Main(string[] args)
{
String line;
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader("C:\\old.txt");
//Read the first line of text
line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//check lines
if (Regex.IsMatch(line, #"\s?(set)\s*(\w+):?(\d)\s+;?(.*)?"))
{
line = Regex.Replace(line, #"\s?(set)\s*(\w+):?(\d)\s+;?(.*)?", "$1 $2:$3 :Integer // $4");
}
if (Regex.IsMatch(line, #"\s?(string)\s*(\w+)\((\d)\)\s*;(.*)"))
{
line = Regex.Replace(line, #"\s?(string)\s*(\w+)\((\d)\)\s*;(.*)", "$1 $2($3) :array [0..$3] of AnsiChar; // $4");
}
//write the lie to console window
Console.WriteLine(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}

You need to use the overloads that include RegexOptions. I can make your stuff work if I include RegexOptions.IgnoreCase.
Regex.IsMatch(given, pattern, RegexOptions.IgnoreCase)
Regex.Replace(given, pattern, replacement, RegexOptions.IgnoreCase)
MSDN Regex.IsMatch Method (String, String, RegexOptions)
MSDN Regex.Replace Method (String, String, String, RegexOptions)

Related

Why is my method adding an extra blank line at the end?

I use the below method to remove all blank lines from a file but it is for some reason adding an extra line at the end of the document?
var tempFileName = Path.GetTempFileName();
try
{
using (var streamReader = new StreamReader(file))
using (var streamWriter = new StreamWriter(tempFileName))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
if (!string.IsNullOrWhiteSpace(line))
streamWriter.WriteLine(line);
}
}
File.Copy(tempFileName, file, true);
}
finally
{
File.Delete(tempFileName);
}
How do I fix this?
Also can the code be made shorter?
Also can the code be made shorter?
A more efficient solution to the other answer:
File.WriteAllLines(file, File.ReadLines("some/path").Where(l => !string.IsNullOrWhiteSpace(l)));
File.ReadLines() is more efficient than File.ReadAllLines() because it allows you to query the IEnumerable<string> without reading it all into memory first.
We then take the resulting IEnumerable<string> from our Where() method and pass it to an overload of File.WriteAllLines() which takes an IEnumerable<string> as its second parameter.
StreamWriter.WriteLine() will always append a new line (a carriage return, line feed pair) after the string, so I assume that's what you're referring to. To me, it's normal and best to have the last line followed by a new line. But if you don't want it, don't write one.
As far as the length of your code, it looks about right to me. If it seems to detract from your program logic, just move it into its own method.
For efficiency, you might try deleting the original file and then renaming the temporary file. That would be more efficient than copying the entire file.
var tempFileName = Path.GetTempFileName();
try
{
using (var streamReader = new StreamReader(file))
using (var streamWriter = new StreamWriter(tempFileName))
{
string line;
bool isFirstLine = true;
while ((line = streamReader.ReadLine()) != null)
{
if (!string.IsNullOrWhiteSpace(line))
{
if (!isFirstLine)
streamWrite.WriteLine();
streamWriter.Write(line);
isFirstLine = false;
}
}
}
File.Delete(file);
File.Move(tempFileName, file);
}
finally
{
File.Delete(tempFileName);
}
The problem is that StreamReader.ReadLine does not return the line breaks themselves, thus destroying line break information. In other words, those two input files:
File 1: A\r\nB\r\n
File 2: A\r\nB
Will yield the same input to your method. You can't determine that way whether there was a final line break or not.
If you never want a final line break, use Write instead of WriteLine and manually add a line break at the beginning of your loop in every iteration except for the first one:
...
string line;
bool first = true;
while ((line = streamReader.ReadLine()) != null)
{
if (string.IsNullOrWhiteSpace(line))
continue;
if (!first)
streamWriter.WriteLine();
streamWriter.Write(line);
first = false;
}
...

How to read the text from another computer

I have tried to read the file from other computer using the IP address, but i could not able to read that one.It's raised the exception like "Could not find a part of the path 'E:\IPFile_Read\IPFile_Read\bin\Debug\#\IPAddress\Test\News.txt'"
Code:
{
StreamReader sr = new StreamReader("#\\IPaddress\\Test\\News.txt");
line = sr.ReadLine();
while (line != null)
{
text_Data.Text = line;
line = sr.ReadLine();
}
sr.Close();
Console.ReadLine();
}
How can i read the text file from another computer.
"#\\IPaddress\\Test\\News.txt" should be #"\\IPaddress\Test\News.txt". For verbatim strings, the # goes before the opening quote, and if you're using a verbatim string, you don't need to escape the slashes. The UNC prefix still needs the \\, because it really does have two backslashes.

With StreamWriter doesn't work \n (C#)

I have a problem with the C# Stream Writer.
I use the following Code:
//Constructor
public EditorTXTFile
{
FileStream f = File.Create(System.IO.Directory.GetCurrentDirectory() + "\\Output.txt");
f.Close();
}
//Function AddText
public void AddLogFileText(string text)
{
string text = "l1\n\rl2\n\rl3\n\nl5";
StreamWriter writer = new StreamWriter(System.IO.Directory.GetCurrentDirectory() + "\\Output.txt", true);
writer.Write(text);
writer.Close();
}
When I open Output.txt it shows for \n or \r a █(which means not showable symbol) and the whole string is in one line...
Later should the text hand over the function, so I can't write the text with .WriteLine because I don't know if the actual string is on the same line or in a new line.
What make I wrong?
Thanks for any help.
Use Environment.NewLine as line separator or "\r\n" if you want to do it by hand.
Line Separator(newLine) is \r\n not \n\r,
change your text as :
string text = "l1\r\nl2\r\nl3\r\nl5";
Try string text = #"l1\n\rl2\n\rl3\n\nl5";. To prevent character stuffing.
This is binary format:
writer.Write(text);
This is line sequential format:
writer.WriteLine(text);
You have to use WriteLine format...
You can use Environment.NewLine like this:
streamWriter.Write(String.Concat(Enumerable.Repeat(Environment.NewLine, n).ToArray()));
i tried to write a class and seprate "\n"s
but i found rich text box!!
yeah! it works:
RichTextBox rch = new RichTextBox();
rch.Text = cmn;
foreach (string l in rch.Lines)
strw.WriteLine(l);

C# method to read text error log file

I am trying to read a file I create that contains all the logs lines throughout my program. I have the following cod:
private string ReadEmailLog(string EmailLog)
{
TextReader tr = new StreamReader(EmailLog);
tr.ReadLine();
tr.Close();
}
I need to read the EmailLog file, every line of it, and then put return it into a string called message. How would I get this method to return the whole log file, every line?
You can use File.ReadAllText or File.ReadAllLines.
If you're using .NET 4.0, you can also use File.ReadLines:
var files = from file in Directory.EnumerateFiles(#"c:\",
"*.txt", SearchOption.AllDirectories)
from line in File.ReadLines(file)
where line.Contains("Microsoft")
select new
{
File = file,
Line = line
};
foreach (var f in files)
{
Console.WriteLine("{0}\t{1}", f.File, f.Line);
}
This allows you to make file I/O part of a LINQ operation.
Try
tr.ReadToEnd();
which will return a string that contains all the content of your file.
TextReader.ReadToEnd Method
If you want to get the lines in a string[], then
tr.ReadToEnd().Split("\n");
should do it, while it will separate the lines to the "\n" character, which represents a carriage return and line feed combined characters (new line character).
simply use:
String text = tr.ReadToEnd();
You can read all the contents or the log and return it. For example:
private string void ReadEmailLog(string EmailLog)
{
using(StreamReader logreader = new StreamReader(EmailLog))
{
return logreader.ReadToEnd();
}
}
Or if you want each line one at a time:
private IEnumerable<string> ReadEmailLogLines(string EmailLog)
{
using(StreamReader logreader = new StreamReader(EmailLog))
{
string line = logreader.ReadLine();
while(line != null)
{
yield return line;
}
}
}
tr.ReadToEnd(); //read whole file at once
// or line by line
While ( ! tr.EOF)
tr.ReadLine()//

How can I edit a text file using C#?

Lets say i have a text file with following content:
Hello!
How are you?
I want to call the file via a simple application that produces an output file with the following contents:
buildLetter.Append("Hello!").AppendLine();
buildLetter.Append("How are you?").AppendLine();
As you see, every line should be put between " ".
Any help will be appreciated.
void ConvertFile(string inPath, string outPath)
{
using (var reader = new StreamReader(inPath))
using (var writer = new StreamWriter (outPath))
{
string line = reader.ReadLine();
while (line != null)
{
writer.WriteLine("buildLetter.Append(\"{0}\").AppendLine();",line.Trim());
line = reader.ReadLine ();
}
}
}
You should add some I/O exception handling on your own.
If you want to append "" to each line you could try combining the ReadAllLines and WriteAllLines methods:
File.WriteAllLines(
"output.txt",
File
.ReadAllLines("input.txt")
.Select(line => string.Format("\"{0}\"", line))
.ToArray()
);
Notice that this loads the whole file contents into memory so it wouldn't work well with very large files. In this case stream readers and writers are more adapted.
Use the StreamReader class from System.IO
Refer this link for sample code
All you probably need to do is change the line
Console.WriteLine(sr.ReadLine());
to
Console.WriteLine(""""" + sr.ReadLine() + """""); // handwritten code - not tested :-)
For a small text files this works for me.
private void EditFile(string path, string oldText, string newText)
{
string content = File.ReadAllText(path);
content = contenido.Replace(oldText, newText);
File.WriteAllText(path, content);
}

Categories