How to read the text from another computer - c#

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.

Related

Unable to read textfile with special characters from a directory

I'm trying to read a textfile name with special characters(Ex: Student_*_Details.txt) from a directory. When I try to read them it says it has illegal characters in the path as the textfile name has these special characters and unable to read the file.
Code:
using (StreamReader streamReader = new StreamReader(#"\\NKR1009FHN\Student_*_Details.txt"))
I' have used the below set of codes to remove the illegal characters from the filename. But in the streamReader if fails as the special characters are getting replaced and unable to find the file since the actual filename got changed due to the below method used.
private static string GetValidFileName(string fileName)
{
String ret = Regex.Replace(fileName.Trim(), "[^A-Za-z0-9_. ]+", "")
return ret.Replace(" ", String.Empty);
}
Is there any workaround to get this fixed?
Really appreciate suggestions.

I want to read the text file up to the empty line and then delete the text that i have read from it

I have this kind of text file show below. I want to read this file up to the empty line and shows that lines in the message box and then delete the text lines including the empty line that I have just read and same process will repeats until the whole file has been read. I have just not been able to read a single line though.
**Hi**
**Hello**
**How are you?
I am fine.**
**And how about you?
Me too fine
Whats going on.**
Here is code sample.
StreamReader sr = new StreamReader(fileNameAndPath);
string line;
try
{
while ((line = sr.ReadLine()) != null)
{
if(line.StartsWith(null))
{
MessageBox.Show(line);
}
sr.Close();
}
}
catch
{
MessageBox.Show("Got empty line while reading a file");
}
StartsWith() cant be passed null to.
This should work:
StreamReader sr = new StreamReader(fileNameAndPath);
string line;
try
{
while ((line = sr.ReadLine()) != null)
{
if(line == null || line == "")
{
MessageBox.Show(line);
}
sr.Close();
}
}
catch
{
MessageBox.Show("Got empty line while reading a file");
}
So a couple things:
There is a difference between a null string and an empty string. You can think of a string like a cookie jar (where characters are the cookies)... An empty string (e.g. string.empty or "") is a cookie jar that has no cookies in it. Whereas null means there is no cookie jar at all. When you read a file line, it always returns a string, as long as there is a line to read. So an empty line comes back as an empty string.
With that being said, while it is true that an empty line starts with nothing, it is not checking the exact thing you want to know. Coding solutions that do
almost the same thing" will get you in a lot of trouble later in life. A more appropriate check would be something like string.IsNullOrEmpty(line)
Finally, if you want to "delete part of the file", I would recommend actually you "remove all of the file, and then only write the part you want to remain". So what you should do is read the entire file into a List<string>. Then, remove the items in the List you don't want. After that, overwrite the file with the remaining items in the List. You can read and write to a file at the same time, but I personally find it messy, and I think it couples your logic. But the biggest point (in both cases) to help you look up how to do it is: Deleting info from a file is considered writing to the file. So look up how to write to a file to delete stuff from it.
You can't pass null to StartsWith(). See here: https://msdn.microsoft.com/en-us/library/baketfxw(v=vs.110).aspx
Suggest that what you're after is
if (string.IsNullOrEmpty(line))
{
...
}

Difference in number of lines in Editpad Lite and Windows notepad

I have a text file which when opened in Editpad Lite show the number of lines as 2754813 and when it is opened in Windows Notepad showing the number of lines as 2713520. When I read it with a C# programme, it shows the number of lines contained in the text file as 2713520 i.e. the same as in notepad. Wordwrap is turned off in both cases This prevents me from matching the lines with Editpad text file. Would anyone please offer their valuable comment.
int b = 0;
using (StreamWriter Writer = new StreamWriter(path_to_textfile.txt"))
{
using (StreamReader Reader = new StreamReader(lisfile))
{
while ((line = Reader.ReadLine()) != null)
{
Match match = Regex.Match(line, #"");//line break symbol between quotes.
if (match.Success)
{
b++;
if (b == 100000) //I got the count of lines correctly.
{
Writer.WriteLine(line);
}
}
else
{
//Writer.WriteLine(line);
}
}
}
}

C# regex syntax

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)

Sending a multiline string over NamedPipe?

How can I send a multiline string with blank lines over a NamedPipe?
If I send a string
string text= #"line 1
line2
line four
";
StreamWriter sw = new StreamWriter(client);
sw.Write(text);
I get on the server side only "line 1":
StreamReader sr = new StreamReader(server);
string message = sr.ReadLine();
When I try something like this
StringBuilder message = new StringBuilder();
string line;
while ((line = sr.ReadLine()) != null)
{
message.Append(line + Environment.NewLine);
}
It hangs in the loop while the client is connected and only releases when the client disconnects.
Any ideas how I can get the whole string without hanging in this loop?
I need to to process the string and return it on the same way to the client.
It's important that I keep the original formatting of the string including blank lines and whitespace.
StreamReader is a line-oriented reader. It will read the first line (terminated by a newline). If you want the rest of the text, you have to issue multiple readlines. That is:
StreamReader sr = new StreamReader(server);
string message = sr.ReadLine(); // will get "line1"
string message2 = sr.ReadLine(); // will get "line2"
You don't want to "read to end" on a network stream, because that's going to hang the reader until the server closes the connection. That might be a very long time and could overflow a buffer.
Typically, you'll see this:
NetworkStream stream = CreateNetworkStream(); // however you're creating the stream
using (StreamReader reader = new StreamReader(stream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// process line received from stream
}
}
That gives you each line as it's received, and will terminate when the server closes the stream.
If you want the reader to process the entire multi-line string as a single entity, you can't reliably do it with StreamReader. You'll probably want to use a BinaryWriter on the server and a BinaryReader on the client.
Why not just call ReadToEnd() on StreamReader?
StreamReader sr = new StreamReader(server);
string message = sr.ReadToEnd();
I accomplished sending multiple line messages over a named pipe by using token substitution to replace all \r and \n in the message with tokens like {cr} and {lf} thus converting multiple lines messages into 1 line.
Of course, I needed to do the reverse conversion of the receiver side.
The assumption is that the substituted tokens will never be found in the source text.
You can make sure that this happens by also substituting all "{" with {lp}. That way the "{" becomes your escape character.
You can use Regex to make these Replacements.
That worked great and allowed me to use StreamReader.

Categories