Convert a node.js script to C# - c#

I have this function in Node.js
let inPath = process.argv[2] || 'file.txt';
let outPath = process.argv[3] || 'result.txt';
fs.open(inPath, 'r', (errIn, fdIn) => {
fs.open(outPath, 'w', (errOut, fdOut) => {
let buffer = Buffer.alloc(1);
while (true) {
let num = fs.readSync(fdIn, buffer, 0, 1, null);
if (num === 0) break;
fs.writeSync(fdOut, Buffer.from([255-buffer[0]]), 0, 1, null);
}
});
});
What would be the equivalent in C#?
My code so far. I do not know what is the equivalent code in C# to minus byte of a character. Thank you in advanced!
var inPath = "file.txt";
var outPath = "result.txt";
string result = string.Empty;
using (StreamReader file = new StreamReader(#inPath))
{
while (!file.EndOfStream)
{
string line = file.ReadLine();
foreach (char letter in line)
{
//letter = Buffer.from([255-buffer[0]]);
result += letter;
}
}
File.WriteAllText(outPath, result);
}

var inPath = "file.txt";
var outPath = "result.txt";
//Converted
using (var fdIn = new FileStream(inPath,FileMode.Open))
{
using (var fdOut = new FileStream(outPath, FileMode.OpenOrCreate))
{
var buffer = new byte[1];
var readCount = 0;
while (true)
{
readCount += fdIn.Read(buffer,0,1);
buffer[0] = (byte)(255 - buffer[0]);
fdOut.Write(buffer);
if (readCount == fdIn.Length)
break;
}
}
}
...
//Same code but all file loaded into memory, processed and after this saved
var input = File.ReadAllBytes(inPath);
for (int i = 0; i < input.Length; i++)
{
input[i] = (byte)(255 - input[i]);
}
File.WriteAllBytes(outPath, input);

Same code but with BinaryReader and BinaryWriter
var inPath = "file.txt";
var outPath = "result.txt";
using (BinaryReader fileIn = new BinaryReader(new StreamReader(#inPath).BaseStream))
using (BinaryWriter fileOut = new BinaryWriter(new StreamWriter(#outPath).BaseStream))
{
while (fileIn.BaseStream.Position != fileIn.BaseStream.Length)
{
var #byte = fileIn.ReadByte();
fileOut.Write((byte)(255 - #byte));
}
}

Related

Problem Read file with US-Ascii Encoding in Dotnet 5? (Work on Dotnet Fx 4.6.2)

i have a code like this:
int fLen = FileSystem.FreeFile();
FileSystem.FileOpen(fLen, txtFilename.Text, OpenMode.Binary, OpenAccess.Read, OpenShare.Shared, -1);
tmp = new String(' ', Convert.ToInt32(FileSystem.FileLen(txtFilename.Text)));
FileSystem.FileGet(fLen, ref tmp, -1, false);
FileSystem.FileClose(fLen);
i have platform dotnet framework 4.6.2, , the variable tmp has result:
xƒ{‚{{{{{\u007f{\u007f{~{|x‡x„zzzzzzzzzzzzzz{€{zxƒ{|{z{{{\u007fz‡{z{ƒz‡{z{‚zz{{{\u0081{„{{{}{„{}{|xƒ{{xƒ{|xƒ{{xƒ{zx‡x
when i upgrade my winforms to the dotnet 5, the variable tmp has result:
x�{�{{{{{\u007f{\u007f{~{|x�x�zzzzzzzzzzzzzz{�{zx�{|{z{{{\u007fz�{z{�z�{z{�zz{{{�{�{{{}{�{}{|x�{{x�{|x�{{x�{zx�x�zzzzzzzzzzzzzzzz{{x�{|{z{{{\u007fz
whats wrong with dotnet 5? is it change the formatting when i read file text?
the original text file is: (i copy paste from notepad)
xƒ{‚{{{{{{{~{|x‡x„zzzzzzzzzzzzzz{€{zxƒ{|{z{{{z‡{z{ƒz‡{z{‚zz{{{{„{{{}{„{}{|xƒ{{xƒ{|xƒ{{xƒ
i use binaryreader, not working too.
var eee = Encoding.UTF7;
StringBuilder sb = new StringBuilder();
FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
//creating BinaryReader using Stream object
using BinaryReader reader = new BinaryReader(stream, eee);
var tes = eee.GetString(eee.GetBytes(reader.ReadString()));
the encoding is : "US-ASCII"
any help will be appreciated.
UPDATE:
the complete code from sample BioBridgeSDK:
private void btnDecryptAttLog_Click(object sender, EventArgs e)
{
string val1 = "";
string val2 = "";
string tmp = "";
Form4 myForm4 = new Form4();
int fLen = FileSystem.FreeFile();
FileSystem.FileOpen(fLen, txtFilename.Text, OpenMode.Binary, OpenAccess.Read, OpenShare.Shared, -1);
tmp = new String(' ', Convert.ToInt32(FileSystem.FileLen(txtFilename.Text)));
FileSystem.FileGet(fLen, ref tmp, -1, false);
FileSystem.FileClose(fLen);
val1 = tmp;
string ReadFile = val1;
int iRead = 10000;
int iPos = 0;
String FullData = "";
String SubData = "";
while (val1.Length > iPos)
{
if ((iPos + iRead) > val1.Length)
iRead = val1.Length - iPos;
val2 = "";
SubData = val1.Substring(iPos, iRead);
if (axBioBridgeSDKv3lib1.DecryptLog(SubData, ref val2) == 0)
FullData = FullData + val2;
iPos = iPos + iRead;
}
myForm4.Text1.Text = FullData;
myForm4.Show();
}
Try passing the encoding.
e.g.
var text = File.ReadAllText("path", Encoding.ASCII);
or for large files use StreamReader. Don't use BinaryReader to read text files
using (var reader = new StreamReader("path", Encoding.ASCII))
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
//Do something with the line.
}
}
Also, In your binary reader code why are you setting the encoding to UTF-7 ?
var eee = Encoding.UTF7;
i already find the solution.
var text = File.ReadAllBytes(file);
var text1 = Encoding.GetEncoding(1252).GetString(text);
thanks for the comment, i find the solution by reading the comment. #jimi
and other comments. thanks.

c# push notification is not working with Turkish character

I want to send notification to IOS from c#. But it does not send message contain Turkish character.
Here is my Pushmessage Function :
public bool PushMessage(string Mess, string DeviceToken, int Badge, string Custom_Field)
{
ConnectToAPNS();
List<string> Key_Value_Custom_Field = new List<string>();
String cToken = DeviceToken;
String cAlert = Mess;
int iBadge = Badge;
// Ready to create the push notification
byte[] buf = new byte[256];
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write(new byte[] { 0, 0, 32 });
byte[] deviceToken = HexToData(cToken);
bw.Write(deviceToken);
bw.Write((byte)0);
// Create the APNS payload - new.caf is an audio file saved in the application bundle on the device
string msg = "";
msg = "{\"aps\":{\"alert\":\"" + cAlert + "\",\"badge\":\"" + iBadge.ToString() + "\",\"sound\":\"noti.aiff\",\"priority\":\"10\"}";
String PayloadMess = "";
if (string.IsNullOrWhiteSpace(Custom_Field) == false)
{
List<string> list_Custom_Field = Custom_Field.Split(';').ToList();
if (list_Custom_Field.Count > 0)
{
for (int indx = 0; indx < list_Custom_Field.Count; indx++)
{
Key_Value_Custom_Field = list_Custom_Field[indx].Split('=').ToList();
if (Key_Value_Custom_Field.Count > 1)
{
if (PayloadMess != "") PayloadMess += ", ";
PayloadMess += "\"" + Key_Value_Custom_Field[0].ToString() + "\":\"" + Key_Value_Custom_Field[1].ToString() + "\"";
}
}
}
}
if (PayloadMess != "")
{
msg += ", " + PayloadMess;
}
msg += "}";
bw.Write((byte)0);
bw.Write((byte)msg.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(msg);
bw.Write(b1);
bw.Flush();
if (sslStream != null)
{
sslStream.Write(ms.ToArray());
return true;
}
return false;
}
Here is the solution:
I change
bw.Write((byte)msg.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(msg);
bw.Write(b1);
to
byte[] bytes = Encoding.UTF8.GetBytes(msg);
// Write the data out to the stream
bw.Write((byte)bytes.Length);
bw.Write(msg.ToCharArray());
Now it works.The problem is character count was wrong.
Probably you just used
Encoding.UTF8.GetBytes(Message);
You can try the following:
Encoding iso = Encoding.GetEncoding("ISO-8859-9"); //Turkish
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);

Hide Text File Into Image

I am trying to hide text file into image with c#
void HideTextFileIntoImage(string TextPath, string ImagePath, string NewFilePath)
{
string[] Text = File.ReadAllLines(TextPath);
string[] Image = File.ReadAllLines(ImagePath);
File.Create(NewFilePath).Close();
string[] NewFile = new string[Text.Length + Image.Length];
for (int i = 0; i < Image.Length; i++)
{
NewFile[i] = Image[i];
}
for (int i = 0; i < Text.Length; i++)
{
NewFile[i + Image.Length] = Text[i];
}
StreamWriter sw = new StreamWriter(NewFilePath);
for (int t = 0; t < NewFile.Length; t++)
{
sw.WriteLine(NewFile[t]);
}
sw.Close();
}
But I can't see image after using it. What wrong?
You're trying to treat binary data as though it were text.
Try this instead (completely untested):
void HideTextFileIntoImage(string TextPath, string ImagePath, string NewFilePath)
{
var textBytes = File.ReadAllBytes(TextPath);
var imageBytes = File.ReadAllBytes(ImagePath);
using (var stream = new FileStream(NewFilePath, FileMode.Create)) {
stream.Write(imageBytes, 0, imageBytes.Length);
stream.Write(textBytes, 0, textBytes.Length);
}
}

How to Show a Binary Data in an Image

Actually, I have saved <Binary data> in Database by :
HttpPostedFile PostedFile = Request.Files[m + 2];
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[m + 2].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[m + 2].ContentLength);
}
Now, I wanted to show the <Binary data> in an Image.
I have used a bit code like :
ASPxImage objimg = new ASPxImage();
objimg.ID = "objimg" + (j + 1);
objimg.Width = 100;
objimg.Height = 100;
byte[] buffer = null;
buffer = (byte[])DtChoices.Rows[j]["COLUMN_IMAGE"];
MemoryStream ms = new MemoryStream(buffer);
objimg.Value = System.Drawing.Image.FromStream(ms);
But, I am unable to display Image.Can anyone Help Me?
I have not used the DevExpress controls library, but from the documentation I can gather than the correct class to do this is ASPxBinaryImage. There's an example available on their website at http://www.devexpress.com/Support/Center/Example/Details/E1414
Your control -
<dxe:ASPxBinaryImage ID="ASPxBinaryImage1" runat="server" Value='<%# ConvertOleObjectToByteArray(Eval("Image")) %>'></dxe:ASPxBinaryImage>
The conversion function -
public partial class _Default : System.Web.UI.Page {
const string BITMAP_ID_BLOCK = "BM";
const string JPG_ID_BLOCK = "\u00FF\u00D8\u00FF";
const string PNG_ID_BLOCK = "\u0089PNG\r\n\u001a\n";
const string GIF_ID_BLOCK = "GIF8";
const string TIFF_ID_BLOCK = "II*\u0000";
const int DEFAULT_OLEHEADERSIZE = 78;
public static byte[] ConvertOleObjectToByteArray(object content) {
if (content != null && !(content is DBNull)) {
byte[] oleFieldBytes = (byte[])content;
byte[] imageBytes = null;
// Get a UTF7 Encoded string version
Encoding u8 = Encoding.UTF7;
string strTemp = u8.GetString(oleFieldBytes);
// Get the first 300 characters from the string
string strVTemp = strTemp.Substring(0, 300);
// Search for the block
int iPos = -1;
if (strVTemp.IndexOf(BITMAP_ID_BLOCK) != -1) {
iPos = strVTemp.IndexOf(BITMAP_ID_BLOCK);
} else if (strVTemp.IndexOf(JPG_ID_BLOCK) != -1) {
iPos = strVTemp.IndexOf(JPG_ID_BLOCK);
} else if (strVTemp.IndexOf(PNG_ID_BLOCK) != -1) {
iPos = strVTemp.IndexOf(PNG_ID_BLOCK);
} else if (strVTemp.IndexOf(GIF_ID_BLOCK) != -1) {
iPos = strVTemp.IndexOf(GIF_ID_BLOCK);
} else if (strVTemp.IndexOf(TIFF_ID_BLOCK) != -1) {
iPos = strVTemp.IndexOf(TIFF_ID_BLOCK);
}
// From the position above get the new image
if (iPos == -1) {
iPos = DEFAULT_OLEHEADERSIZE;
}
//Array.Copy(
imageBytes = new byte[oleFieldBytes.LongLength - iPos];
MemoryStream ms = new MemoryStream();
ms.Write(oleFieldBytes, iPos, oleFieldBytes.Length - iPos);
imageBytes = ms.ToArray();
ms.Close();
ms.Dispose();
return imageBytes;
}
return null;
}
}

Download attachment from email

How can I browse the email and download all attachments ?
public string Connect_Email ()
{
string Res = "";
try
{
mailclient = new TcpClient("pop.orange.fr", Convert.ToInt16("110"));
}
catch ( SocketException ExTrhown )
{
Res = "Unable to connect to server 1";
throw new Exception(ExTrhown.Message + "Unable to connect to server 1");
}
ns = mailclient.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
response = sr.ReadLine(); //Get opening POP3 banner
sw.WriteLine("USER " + "xxxxx#orange.fr"); //Send username
sw.Flush();
response = sr.ReadLine();
if ( response.Substring(0, 4) == "-ERR" )
{
Res = "Unable to log into server 2";
}
sw.WriteLine("PASS " + "xxxxx"); //Send password
sw.Flush();
response = sr.ReadLine();
if ( response.Substring(0, 3) == "-ER" )
{
Res = "Unable to log into server 3";
}
return Res;
}
public void Get_Attacht ()
{
string ClientName = "";
#region Chercher Attachment
sw.WriteLine("STAT"); //Send stat command to get number of messages
sw.Flush();
response = sr.ReadLine();
//find number of message
string[] nummess = response.Split(' ');
totmessages = Convert.ToInt16(nummess[1]);
//read emails
for ( int i = 1; i <= totmessages; i++ )
{
msg = null;
sw.WriteLine("top " + i + " 0"); //read header of each message
sw.Flush();
response = sr.ReadLine();
while ( true )
{
response = sr.ReadLine();
if ( response == "." )
break;
msg = msg + response + "\r\n";
}
//read attachment
attachment = null;
if ( Regex.Match(msg, "multipart/mixed").Success )
{
msg = null;
sw.WriteLine("retr " + i.ToString()); //Retrieve entire message
sw.Flush();
response = sr.ReadLine();
while ( true )
{
response = sr.ReadLine();
if ( response == "." )
break;
msg = msg + response + "\r\n";
}
int End = msg.IndexOf(".csv");
string LeFile = msg.Substring(End - 9, 9);
if ( Regex.Match(msg, LeFile + ".csv").Success )
{
data = msg.Split('\r');
startindex = 0;
index = 0;
lastindex = 0;
x = null;
ms = null;
fs = null;
while ( true )
{
attachment = null;
while ( !Regex.Match(data[index].Trim(), "filename").Success )
{
index++;
}
if ( index == data.Length - 1 ) break;
FileName_Email = data[index].Trim().Substring(42).Replace("\"", "");
//find start of attachment data
index++;
while ( data[index].Length != 1 )
{
index++;
}
if ( index == data.Length - 1 ) break;
startindex = index + 1;
//find end of data
index = startindex + 1;
while ( ( !Regex.Match(data[index].Trim(), "--0").Success ) && ( data[index].Length != 1 ) && ( index < data.Length - 1 ) )
{
index++;
}
if ( index == data.Length ) break;
lastindex = index - 2;
for ( int j = startindex; j <= lastindex; j++ )
{
attachment = attachment + data[j];
}
attachment = attachment + "\r\n";
if ( Regex.Match(FileName_Email.ToLower(), "csv").Success )
{
byte[] filebytes = Convert.FromBase64String(attachment);
FileStream LeFS = new FileStream(filePath + "\\testDEC.csv", FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();
break;
}
}
}
}
}
sw.WriteLine("quit"); //quit
sw.Flush();
#endregion
}
It does not work, have you another simple idea ?
Try something like this
using(Pop3 pop3 = new Pop3())
{
pop3.Connect("server");
pop3.UseBestLogin("user", "password");
foreach (string uid in pop3.GetAll())
{
IMail email = new MailBuilder()
.CreateFromEml(pop3.GetMessageByUID(uid));
Console.WriteLine(email.Subject);
// save all attachments to disk
email.Attachments.ForEach(mime => mime.Save(mime.SafeFileName));
}
pop3.Close();
}
// here is a reference link you can use as well
Getting Email Attachments
If you're trying to read e-mail via POP3, I would recommend using the OpenPOP.NET library instead of rolling your own. It's pretty easy to use.
Thanks you all for your contribution. Finally I use POP3:
public string Connect_Email()
{
string Res = "";
try
{
Pop3Client email = new Pop3Client("login", "password", "server");
email.OpenInbox();
while (email.NextEmail())
{
if (email.IsMultipart)
{
IEnumerator enumerator = email.MultipartEnumerator;
while (enumerator.MoveNext())
{
Pop3Component multipart = (Pop3Component)
enumerator.Current;
if (multipart.IsBody)
{
//Console.WriteLine("Multipart body:" + multipart.Name);
}
else
{
//Console.WriteLine("Attachment name=" + multipart.Name); // ... etc
byte[] filebytes = Convert.FromBase64String(multipart.Data);
//Search FileName
int Begin = multipart.ContentType.IndexOf("name=");
string leFileNale = multipart.ContentType.Substring(Begin + 5, 12);
FileStream LeFS = new FileStream(filePath + "\\" + leFileNale, FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();
}
}
}
}
email.CloseConnection();
}
catch (Pop3LoginException)
{
Res = "Vous semblez avoir un problème de connexion!";
}
return Res;
}
It work well, but still I have to find and download the attachement my self.
byte[] filebytes = Convert.FromBase64String(multipart.Data);
//Search FileName
int Begin = multipart.ContentType.IndexOf("name=");
string leFileNale = multipart.ContentType.Substring(Begin + 5, 12);
FileStream LeFS = new FileStream(filePath + "\\" + leFileNale, FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();
This not work more. Use Modern Authentication with Microsoft.Graph after create a cliente secret into AZURE and registered tha application them.

Categories

Resources