Search code examples
c#filebytestream

Convert result of File.ReadAllBytes as File object without actually writing it


One Module reads some files using

File.ReadAllBytes("path")

and stores the result in a database table.

Later I take the result from the table and normaly use

File.WriteAllBytes("outputPath", binary.Data)

to write the file back.

Now I have to change the content of the file. Of course I can write the file to a temp folder, read it back in as a File object, change it, write it back to the destination folder. But is there a smarter way to do that? Create the File object directly out of the binary data?


Solution

  • Got a solution. Its the Encoding Class:

            var binary = GetBinaryFileFromDatabase();
    
            var inputLines = Encoding.Default.GetString(binary).Split('\n');
            var outputLines = new List<string>();
    
            foreach (var line in inputLines)
            {
                var columns = line.Split(';');
                if (columns.Length > 28 && columns[28] != null && columns[28].Length > 0)
                {
                    columns[28] = columns[28].Replace(Path.GetFileName(columns[28]), "SomeValue");
                }
                outputLines.Add(string.Join(";", columns));
            }
            File.WriteAllLines(outputPath, outputLines);
    

    Thanks everybody!