0

I'm trying to modify some code that dumps a specific file and I want to modify the first bytes of the dumped file.

I've already done it in a C equivalent program like this :

[...]
SetFilePointer(hDmpFile, 0, 0, FILE_BEGIN);
WriteFile(hDmpFile, "AA", 2, NULL, NULL);

I want to do the same thing in C# but I got some error regarding the WriteFile() function.

Here's what I've done so far :

[...]
        public enum EMoveMethod : uint
        {
            Begin = 0,
            Current = 1,
            End = 2
        }

        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint SetFilePointer(
            [In] SafeFileHandle hFile,
            [In] int lDistanceToMove,
            [Out] out int lpDistanceToMoveHigh,
            [In] EMoveMethod dwMoveMethod);

        [DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Ansi)]
        public static extern bool WriteFile(
            IntPtr hFile,
            System.Text.StringBuilder lpBuffer,
            uint nNumberOfBytesToWrite,
            out uint lpNumberOfBytesWritten,
            [In] ref System.Threading.NativeOverlapped lpOverlapped);
[...]
            int moveDistanceHighBits = 0;

            uint test = SetFilePointer(hDmpFile, 0, out moveDistanceHighBits, EMoveMethod.Begin);
            uint test2 = WriteFile(hDmpFile, "AA", 2, null, null);
            
            hDmpFile.Dispose();
[...]

Here's the error I got when executing the file :

Unhandled Exception: System.NotImplementedException: The method or operation is not implemented.
   at Foo.Program.WriteFile(SafeFileHandle hDmpFile, String v1, Int32 v2, Object value1, Object value2)
   at Foo.Program.Execute(String[] args)
   at Foo.Program.Main(String[] args)

For the record, I'm an absolute disaster when it comes to coding and I've never done C#...

Darktortue
  • 15
  • 1
  • 6
  • 1
    There is no reason for this P/Invoking; `FileStream.Seek` supports what you want to do quite well. – Jeroen Mostert Nov 03 '22 at 10:19
  • Agree with @JeroenMostert, what you are trying to do can likely be done in pure C# without resorting to manually P/Invoking system calls. – phuzi Nov 03 '22 at 10:21
  • 1
    Take a look at https://stackoverflow.com/questions/44904094/replacing-byte-in-file for an example of how to do this in C# – phuzi Nov 03 '22 at 10:22

0 Answers0