C# irc client streamwriter just send one word - c#

i have source irc client from some site. this is the some code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text.RegularExpressions;
namespace tes_irc
{
class Program
{
static string[] usuarios;
static void Main(string[] args)
{
NetworkStream conexion;
TcpClient irc;
StreamReader leer_datos;
StreamWriter mandar_datos;
string host = "irc.dal.net";
string nickname = "testing";
string canal = "#gsgsge";
string code = "";
leer_datos = new StreamReader(conexion);
mandar_datos = new StreamWriter(conexion);
mandar_datos.WriteLine("NICK " + nickname);
mandar_datos.Flush();
mandar_datos.WriteLine("USER " + nickname + " 1 1 1 1");
mandar_datos.Flush();
mandar_datos.WriteLine("JOIN " + canal);
mandar_datos.Flush();
while (true) // Mi bucle eterno
{
while ((code = leer_datos.ReadLine()) != null)
{
Console.WriteLine("Code : " + code);
Match regex = Regex.Match(code, "PING(.*)", RegexOptions.IgnoreCase);
if (regex.Success)
{
Console.WriteLine("hehe");
string te_doy_pong = "PONG " + regex.Groups[1].Value;
mandar_datos.WriteLine(te_doy_pong);
mandar_datos.Flush();
}
regex = Regex.Match(code, ":(.*) 353 (.*) = (.*) :(.*)", RegexOptions.IgnoreCase);
if (regex.Success)
{
string usuarios_lista = regex.Groups[4].Value;
usuarios = usuarios_lista.Split(' ');
foreach (string usuario in usuarios)
{
Console.Write("[+] User : " + usuario);
}
mandar_datos.WriteLine("PRIVMSG" + " " + canal + " " + "Hello World");
mandar_datos.Flush();
}
}
}
}
}
}
Connection is succes, but when i write for send message like "Hello world" just send "Hello". what's wrong with this code? maybe must encode string before? or?please help me. Thanks before :)

The final argument of your IRC command should be prefixed with a colon character (:). Otherwise parsing of the argument will end at the first whitespace.
mandar_datos.WriteLine("PRIVMSG" + " " + canal + " " + ":Hello World");

Related

New line in a string is not works with text file

I have a function to write a message to text file. But when passing a string with 'Environment.NewLine', it is not writes a new line to the text file. Instead it writes '\r\n'.
How to correct this? I have tried with '\n' instead of 'Environment.NewLine'. Still the new line is not coming.
The issue is happens only when passing a string with new line to the function. Like variable 'message'
string message= "First "+Environment.NewLine+" message.";
LogTheDetails(message);
public static void LogTheDetails(String message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\logs";
var directory = new DirectoryInfo(path);
if (directory.Exists == false)
{
directory.Create();
}
string FilePath = path + "/" + currentdate + ".txt";
if (!File.Exists(FilePath)) //FILE WRITING FIRST TIME
{
File.Create(FilePath).Dispose();
using (TextWriter tw = new StreamWriter(FilePath))
{
tw.WriteLine("============================================================\n --Logs--");
}
}
else if (File.Exists(FilePath))//IF FILE ALREADY EXIST - APPEND LINES
{
string testString= "testString"+ Environment.NewLine+ "WithNewLine";
File.AppendAllText(FilePath, "\n============================================================\n");
File.AppendAllText(FilePath, message);
File.AppendAllText(FilePath, testString);
File.AppendAllText(FilePath, "\n============================================================\n");
}
}
Output
============================================================
--Logs--
============================================================
First \r\n message.
testString
WithNewLine
============================================================
Expected Output:
============================================================
--Logs--
============================================================
First
message.
testString
WithNewLine
============================================================
Below piece of code gave the output you are looking for, I tried it in .net 5 console application.
using System;
using System.IO;
namespace ConsoleApp4
{
class Program
{
static string message = "First " + Environment.NewLine + " message.";
static void Main(string[] args)
{
LogTheDetails(message);
Console.WriteLine("Hello World!");
}
public static void LogTheDetails(string message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\logs";
var directory = new DirectoryInfo(path);
if (directory.Exists == false)
{
directory.Create();
}
string currentdate = "test";
string FilePath = path + "/" + currentdate + ".txt";
if (!File.Exists(FilePath)) //FILE WRITING FIRST TIME
{
File.Create(FilePath).Dispose();
using (TextWriter tw = new StreamWriter(FilePath))
{
tw.WriteLine("========================================================\n
--Logs--");
}
}
else if (File.Exists(FilePath))//IF FILE ALREADY EXIST - APPEND
LINES
{
string testString = Environment.NewLine + "testString" +
Environment.NewLine + "WithNewLine";
File.AppendAllText(FilePath,
"\n============================================================\n");
File.AppendAllText(FilePath, message);
File.AppendAllText(FilePath, testString);
File.AppendAllText(FilePath,
"\n============================================================\n");
}
}
}
}

How to add Column and Row header while appending data into CSV file using C#

I'm trying to insert data into CSV file using C# code. With the code I pasted below, I am able to add column header to the CSV file. But I need to add both column and row header in the CSV file for better readability. Please help me on this.
C# Code
string newFileName = "C:\\AlertReportTill_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".csv";
string AlertDetails = fromDate + "," + toDate + "," + Column1's Value + "," + Column2's Value + ","
+ Column3's Value + "," + Environment.NewLine;
if (!System.IO.File.Exists(newFileName))
{
string AlertHeader = "Weekly Report" + Environment.NewLine + "From Date" + "," + "To Date" + "," +
"ColumnHeader1" + "," + "ColumnHeader2" + "," +
"ColumnHeader3" + "," + Environment.NewLine;
System.IO.File.WriteAllText(newFileName, AlertHeader);
} //End of If Statement
System.IO.File.AppendAllText(newFileName, AlertDetails);
For better clarity, I have added an image below to help you understand my question. It would be very helpful if someone can sort this out for me. Thanks in advance.
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication104
{
class Program
{
static void Main(string[] args)
{
string oldFileName = "C:\\AlertReportTill.csv";
string newFileName = string.Format("C:\\AlertReportTill_{0}.csv", DateTime.Now.ToString("yyyyMMdd_hhmmss"));
StreamReader reader = new StreamReader(oldFileName);
if (!System.IO.File.Exists(newFileName))
{
StreamWriter writer = new StreamWriter(newFileName);
writer.WriteLine("Weekly Report");
string AlertHeader = string.Join(",", new string[]
{"",
"ColumnHeader1", "ColumnHeader2", "ColumnHeader3"
});
writer.WriteLine(AlertHeader);
string line = "";
int RowCount = 0;
while ((line = reader.ReadLine()) != null)
{
List<string> AlertDetails = line.Split(new char[] { ',' }).ToList();
AlertDetails.Insert(0, "RowHeader" + ++RowCount);
writer.WriteLine(string.Join(",", AlertDetails));
}
reader.Close();
writer.Flush();
writer.Close();
} //End of If Statement
}
}
}

Taking multiple substrings from a single line in a .txt file in C#

Part of a class assignment I'm working on requires me to take isolate certain parts of a "students" info from a .txt file such as last name, first name, and gpa. While I can get the last name to appear properly, going beyond that is iffy, first names will be cut off or go to the middle initial seemingly randomly. I need help with having consistent cut off points based on markers (apostrophes) in the lines.
this is a sample of the .txt file Students2 which is located in the program's Bin Debug
(LIST (LIST 'Abbott 'Ashley 'J ) '8697387888 'ajabbott#mail.usi.edu 2.3073320999676614 )
(LIST (LIST 'Abbott 'Bradley 'M ) 'NONE 'bmabbott#mail.usi.edu 3.1915725161177115 )
(LIST (LIST 'Abbott 'Ryan 'T ) '8698689793 'rtabbott#mail.usi.edu 3.448215586562192 )
(LIST (LIST 'Abel 'Heather 'M ) '8698689386 'hmabel#mail.usi.edu 3.2517764202656974 )
Hopefully what I meant by markers makes sense, and the info is fake if anyone wondered.
The following is my current code, some of which was provided in an example.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication61
{
class Program
{
static void Main(string[] args)
{
StreamReader inFile;
string inLine;
if (File.Exists("Students2.txt"))
{
try
{
using (StreamWriter Malachi = File.AppendText("Students2.txt"))
{
Malachi.WriteLine("(LIST (LIST 'Constant 'Malachi 'J ) '1832878847 'mconstant#mail.usi.edu 4.0000000000000000 )");
}
inFile = new StreamReader("Students2.txt");
while ((inLine = inFile.ReadLine()) != null)
{
int start = inLine.IndexOf("'");
if (start >= 0)
{
inLine = inLine.Substring(start);
int end = inLine.IndexOf(" ");
string lastname = inLine.Substring(0, end);
int endTwo = inLine.IndexOf(" ");
string firstname = inLine.Substring(end, endTwo);
int endThree = inLine.IndexOf(" ");
string email = inLine.Substring(endTwo, endThree);
Console.WriteLine( lastname + firstname );
}
}
}
catch (System.IO.IOException exc)
{
Console.WriteLine("Error");
}
}
}
}
}
Again I'd like to know what I'm doing wrong in regards to cutting off at specific points. Any and all help is greatly appreciated.
you can use the split function and replace function to get what you are looking for something like this
string test = "(LIST (LIST 'Constant 'Malachi 'J ) '1832878847 'mconstant#mail.usi.edu 4.0000000000000000 )";
test = test.Replace(")","");
string[] abc = test.Split(new string[] { "'" }, StringSplitOptions.None);
Console.WriteLine("Last Name =" + abc[1]);
Console.WriteLine("First Name =" + abc[2]);
Console.WriteLine("Middle Initial =" + abc[3]);
Console.WriteLine("Email gpa =" + abc[abc.Length-1]);
UPDATE
In case there is no apostrophe for gpa you can get those values as below, just replace the last line with this
Console.WriteLine("Email =" + (abc[abc.Length-1]).Split(' ')[0]);
Console.WriteLine("gpa =" + (abc[abc.Length-1]).Split(' ')[1]);
Here is a fiddle for it https://dotnetfiddle.net/vJYLXW
you need to update inLine every time you take off substring like -
int start = inLine.IndexOf("'");
if (start >= 0)
{
inLine = inLine.Substring(start);
int end = inLine.IndexOf(" ");
string lastname = inLine.Substring(0, end);
inLine = inLine.Substring(end + 1);
int endTwo = inLine.IndexOf(" ");
string firstname = inLine.Substring(end, endTwo);
inLine = inLine.Substring(endTwo + 1);
int endThree = inLine.IndexOf(" ");
string email = inLine.Substring(endTwo, endThree);
.
.
}
and so on.....
OR you take find next space after end point of first string like this -
int start = inLine.IndexOf("'");
if (start >= 0)
{
inLine = inLine.Substring(start);
int end = inLine.IndexOf(" ");
string lastname = inLine.Substring(0, end);
int endTwo = inLine.IndexOf(' ', end + 1);
string firstname = inLine.Substring(end, endTwo - end);
int endThree = inLine.IndexOf(' ', endTwo + 1);
string middleinitial = inLine.Substring(endTwo, endThree - endTwo);
endThree += 2; // to escape ')' after middle initial
int endFour = inLine.IndexOf(' ', endThree + 1);
string phone = inLine.Substring(endThree, endFour - endThree);
int endFive = inLine.IndexOf(' ', endFour + 1);
string email = inLine.Substring(endFour, endFive - endFour);
int endSix = inLine.IndexOf(' ', endFive + 1);
string gpa = inLine.Substring(endFive, endSix - endFive);
Console.WriteLine("Last Name - " + lastname);
Console.WriteLine("First Name - " + firstname);
Console.WriteLine("Middle Initial - " + middleinitial);
Console.WriteLine("Phone - " + phone);
Console.WriteLine("Email - " + email);
Console.WriteLine("GPA - " + gpa);
}
But I would recommend string split option. Read about String.Split Method
while ((inLine = inFile.ReadLine()) != null)
{
var splits = inLine.Split(new[] { ' ', '\'' }, StringSplitOptions.RemoveEmptyEntries);
if (splits.Length > 0)
{
Console.WriteLine("Last Name - " + splits[2]);
Console.WriteLine("First Name - " + splits[3]);
Console.WriteLine("Middle Initial - " + splits[4]);
Console.WriteLine("Phone - " + splits[6]);
Console.WriteLine("Email - " + splits[7]);
Console.WriteLine("GPA - " + splits[8]);
}
Console.WriteLine("------------------------------------------------------");
}
It is much easier to get the desired fields with regexp:
Regex rPattern= new Regex(#"\'([^'\s]+)[\'\s]+([^'\s]+)[\'\s]+([^'\s]+)[\'\s]+\)[\'\s]+([^'\s]+)[\'\s]+([^'\s]+)[\'\s]+([^'\s]+)");
....
Match m = rPattern.Match(inLine );
if(m.Success)
{
string lastname = m.Groups[1].Value;
string firstname = m.Groups[2].Value;
string middlename = m.Groups[3].Value;
string phone = m.Groups[4].Value;
string email = m.Groups[5].Value;
string somenumber = m.Groups[6].Value;
}
Your code can be something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
//PTK: don't forget include following line. IT'S IMPORTANT !!!
using System.Text.RegularExpressions;
namespace ConsoleApplication61
{
class Program
{
static void Main(string[] args)
{
StreamReader inFile;
string inLine;
//PTK: patern for your fields
Regex rPattern= new Regex(#"\'([^'\s]+)[\'\s]+([^'\s]+)[\'\s]+([^'\s]+)[\'\s]+\)[\'\s]+([^'\s]+)[\'\s]+([^'\s]+)[\'\s]+([^'\s]+)");
if (File.Exists("Students2.txt"))
{
try
{
using (StreamWriter Malachi = File.AppendText("Students2.txt"))
{
Malachi.WriteLine("(LIST (LIST 'Constant 'Malachi 'J ) '1832878847 'mconstant#mail.usi.edu 4.0000000000000000 )");
}
inFile = new StreamReader("Students2.txt");
while ((inLine = inFile.ReadLine()) != null)
{
//PTK: match the current line with the pattern
Match m = rPattern.Match(inLine );
if(m.Success)
{
string lastname = m.Groups[1].Value;
string firstname = m.Groups[2].Value;
string middlename = m.Groups[3].Value;
string phone = m.Groups[4].Value;
string email = m.Groups[5].Value;
string somenumber = m.Groups[6].Value;
Console.WriteLine( lastname + firstname );
}
}
}
catch (System.IO.IOException exc)
{
Console.WriteLine("Error");
}
}
}
}
}
You can see working demo here: https://dotnetfiddle.net/FrU4l5

Console.WriteLine is blank

I have a strange problem. I wrote a .net 2.0 console application running on Windows Server 2008 R2 that processes a file that's passed in via args When I run it by hand and pass in a file, I don't get an output. Nothing. No errors or exception of any kind. Event log is clear. I would expect that I get some output from the exe. I also have a Console.WriteLine in my catch statement. But again, no output whatsoever. Any ideas why?
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.IO;
namespace RTDXCentralFileTransmit
{
class Program
{
static void Main(string[] args)
{
try
{
if (args.Length < 1)
{
Console.WriteLine("File name is required");
logit("File name is required");
return;
}
string filename = args[0];
Console.WriteLine("Now doing " + filename);
logit("Now doing " + filename);
if (!File.Exists(filename))
{
Console.WriteLine("File " + filename + " does not exists. Exiting.");
logit("File " + filename + " does not exists. Exiting.");
File.WriteAllText("Error.txt", "File " + filename + " does not exists. Exiting.");
return;
}
string fileplain = File.ReadAllText(filename);
string file64 = EncodeTo64(fileplain);
if (string.IsNullOrEmpty(file64))
{
Console.WriteLine("File " + filename + " is empty. Exiting");
logit("File " + filename + " is empty. Exiting");
File.WriteAllText("Error.txt", "File " + filename + " is empty. Exiting");
return;
}
FileInfo fi = new FileInfo(filename);
com.xxxxxxxxxxxxxxxxxx.api.Dispatch dis = new com.xxxxxxxxxxxxxxxx.api.Dispatch();
com.xxxxxxxxxxxx.api.FunnelResult fr = dis.Funnel(file64, fi.Name);
if (fr.Success)
{
Console.WriteLine("Success! " + fr.Result);
logit("Success! Response from the server: " + fr.Result);
File.WriteAllText("Success.txt", fr.Result);
return;
} else
{
Console.WriteLine("Failed!! " + fr.Result);
logit("Failed!! " + fr.Result);
File.WriteAllText("Error.txt", "Transmission Failed! " + fr.Result);
}
logit("Exiting for " + filename);
Environment.Exit(0);
} catch (Exception e)
{
Console.WriteLine("Error. " + e.ToString());
return;
}
}
static void logit (string s)
{
File.AppendAllText("FileTransmit.log",DateTime.Now.ToString() + ":" + s + Environment.NewLine);
}
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
}
}
I found it. The issue was between the chair and the computer.
The project that I cloned, even though it had tons of Console.WriteLine, it was actually was being built as Windows Application. That explains why we have no output for the Console.WriteLine.
Since it was being build as windows application, the console doesn't wait for the program to finish. It returns right away - which totally threw me off seeing that many console.writelines. However, the program is still running and, with a large file, it takes a while to post it to the remote server. After waiting a minute or two all of 10 MB file was transmitted successfully as it was indicated in the logs.

Foreach result in textbox

please view the code provided by Microsoft below:
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Microsoft.Translator.Samples
{
class TranslateArraySample
{
public static async Task Run(string authToken)
{
var from = "en";
var to = "es";
var translateArraySourceTexts = new []
{
"The answer lies in machine translation.",
"the best machine translation technology cannot always provide translations tailored to a site or users like a human ",
"Simply copy and paste a code snippet anywhere "
};
var uri = "https://api.microsofttranslator.com/v2/Http.svc/TranslateArray";
var body = "<TranslateArrayRequest>" +
"<AppId />" +
"<From>{0}</From>" +
"<Options>" +
" <Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">{1}</ContentType>" +
"<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"</Options>" +
"<Texts>" +
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{2}</string>" +
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{3}</string>" +
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{4}</string>" +
"</Texts>" +
"<To>{5}</To>" +
"</TranslateArrayRequest>";
string requestBody = string.Format(body, from, "text/plain", translateArraySourceTexts[0], translateArraySourceTexts[1], translateArraySourceTexts[2], to);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(uri);
request.Content = new StringContent(requestBody, Encoding.UTF8, "text/xml");
request.Headers.Add("Authorization", authToken);
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
switch (response.StatusCode)
{
case HttpStatusCode.OK:
Console.WriteLine("Request status is OK. Result of translate array method is:");
var doc = XDocument.Parse(responseBody);
var ns = XNamespace.Get("http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2");
var sourceTextCounter = 0;
foreach (XElement xe in doc.Descendants(ns + "TranslateArrayResponse"))
{
foreach (var node in xe.Elements(ns + "TranslatedText"))
{
**Console.WriteLine("\n\nSource text: {0}\nTranslated Text: {1}", translateArraySourceTexts[sourceTextCounter], node.Value);**
}
sourceTextCounter++;
}
break;
default:
Console.WriteLine("Request status code is: {0}.", response.StatusCode);
Console.WriteLine("Request error message: {0}.", responseBody);
break;
}
}
}
}
}
Please look at the ** line, node.value is the result I want. According to the code, we will have 3 sentences translated from the string array above. However, I want it to display in a textbox. let say I have a textbox with ID = textbox.
I have tried using this :
foreach (var node in xe.Elements(ns + "TranslatedText"))
{
textbox.Text=node.value;
}
sourceTextCounter++;
However, the result only for the last sentence.
Please share your thought how to do it!
Try this:
foreach (var node in xe.Elements(ns + "TranslatedText"))
{
textbox.Text += node.value + " ";
}
Because you're always overwriting .Text you need to concatenate with something like:
textbox.Text += node.value + Environment.NewLine;
This would add your node.value and a newline character for each node found.
EDIT: Also want to state that Environment.NewLine is ignored if the Multiline property of the textbox is false.

Categories