0

c# から p/invoke を使用して、ローカル HD に直接書き込みます。ドライブはフォーマットされていますが、データが含まれていません。私がやろうとしているのは、ドライブが完全にいっぱいになるまで、ドライブに 512 バイトの 0 を書き込むことだけです。

コード:

for (double idx = 0; idx < TotalSectors; idx++)
    {
        File.Write(writeBuffer, (uint)writeBuffer.Length);  // write the buffer
        int val = pos += (int.Parse(BPS.ToString()) * int.Parse(idx.ToString()));
        File.MoveFilePointer(val);
        Application.DoEvents();
    }

ご覧のとおり、すべてのセクターが書き込まれるまでプロセスを繰り返します。ただし、何らかの理由で 8 回繰り返した後、「アクセスが拒否されました」というエラーが表示されます。

何か案は?

編集 Xanatos のおかげで、ばかげたファイル位置の更新が修正されました。ただし、File.MoveFilePointer() メソッドは int を取ります。だから私は現在valを(int)にキャストしています。このメソッドは、「アクセスが拒否されました」例外をスローする前に 14 回反復するようになりました。

編集 2 借用コード

write メソッドは次のようになります。

 public uint Write(byte[] buffer, uint cbToWrite)
    {
        // returns bytes read
        uint cbThatWereWritten = 0;
        if (!WriteFile(_hFile, buffer, cbToWrite,
         ref cbThatWereWritten, IntPtr.Zero))
            ThrowLastWin32Err();
        return cbThatWereWritten;
    }

File.MoveFilePointer メソッドは次のようになります。

public void MoveFilePointer(int cbToMove,
     MoveMethod fMoveMethod)
    {
        if (_hFile != null)
            if (SetFilePointer(_hFile, cbToMove, IntPtr.Zero,
             fMoveMethod) == INVALID_SET_FILE_POINTER)
                ThrowLastWin32Err();
    }
4

1 に答える 1

3
int bps = ... // Use int!
long TotalSectors = ... // use long!
long pos = 0; // use long!

for (long idx = 0; idx < TotalSectors; idx++)
{
    File.Write(writeBuffer, (uint)writeBuffer.Length);  // write the buffer
    pos += bps;
    // File.MoveFilePointer(pos); // Useless, the file pointer will be moved
                                  // by the File.Write
    Application.DoEvents();
}

終わり!増えposすぎ!

val = pos += (int.Parse(BPS.ToString()) * int.Parse(idx.ToString()));

を無視しvalParse(...ToString)それを無視します:

pos += BPS * idx;

そう

idx = 0, pos += 0 (pos = 0), // here it's already wrong! you are initializing twice 
                             // the same sector!
idx = 1, pos += 1 * 512 (pos = 512), 
idx = 2, pos += 2 * 512 (pos = 1536) WRONG!

補足として、.net では alongは 64 ビットなので、ハードディスクのセクター数またはそのサイズに十分な大きさです。

于 2013-08-16T07:19:24.147 に答える