Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert a node.js script to 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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading