0

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
  • 1
    What is task being done by node JS code? Commented Jun 21, 2022 at 12:21
  • @Chetan in Nodejs, that script will invert byte of all character by 255 Commented Jun 21, 2022 at 12:23

2 Answers 2

1
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);
Sign up to request clarification or add additional context in comments.

1 Comment

Your welcome, @takatto . As improvement you can write readCount != fdIn.Length to while condition and remove if statement.
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));
    }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.