Home > Blockchain >  Convert a node.js script to C#
Convert a node.js script to C#

Time:06-22

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

CodePudding user response:

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

CodePudding user response:

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