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!

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

2 Answers

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest