Hi,
I am writing a code to restore encrypted files using c#.NET
All my functions are successful.But in the target the file shows size 0KB.
i.e.,even if ReadFile API reads all the bytes,they are not written using the
call back function.Can someone please suggest me what am I doing wrong?
Below is my code.
private delegate int ImportCallBack(IntPtr pbdata,IntPtr
pvCallbackContext,int ulLength);
[DllImport("advapi32.dll", SetLastError=true) ]
private extern static int
WriteEncryptedFileRaw([MarshalAs(UnmanagedType.FunctionPtr)] ImportCallBack
pfImportCallback,
IntPtr pvCallbackContext,IntPtr pvContext);
[DllImport("advapi32.dll", CharSet=CharSet.Auto,SetLastError=true) ]
public extern static int
OpenEncryptedFileRaw([MarshalAs(UnmanagedType.LPTStr)]
string lpFileName,int ulFlags,out IntPtr pvContext);
[DllImport("advapi32.dll", SetLastError=true) ]
public extern static void CloseEncryptedFileRaw(IntPtr pvContext);
[DllImport("kernel32.dll", SetLastError=true)]
static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess,
uint dwShareMode, uint lpSecurityAttributes,uint dwCreationDisposition, uint
dwFlagsAndAttributes, uint hTemplateFile);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
public static void start()
{
string sSourceFile = @"D:\errr.txt"; //Encrypted file to be restored
string sTargetFile = @"\\Server1\c$\errr1.txt";
hRawFile = CreateFile(sSourceFile,GENERIC_READ, 0, 0,
OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if(hRawFile.ToInt32() == INVALID_HANDLE_VALUE)
{
Console.WriteLine("Error Opening File : " + sSourceFile );
CloseEncryptedFileRaw(pvContext);
return;
}
if(OpenEncryptedFileRaw(sTargetFile,CREATE_FOR_IMPORT,out pvContext)!= 0)
{
Console.WriteLine("Open File Failed with {0}",
Marshal.GetLastWin32Error());
Console.WriteLine("Error Opening File : " + sTargetFile);
return;
}
ImportCallBack Imcb = new ImportCallBack(WriteCallBack);
int i = WriteEncryptedFileRaw(Imcb,hRawFile,pvContext);
CloseEncryptedFileRaw(pvContext);
CloseHandle(hRawFile);
}
public static int WriteCallBack(IntPtr pbdata, IntPtr pvCallbackContext ,
int ulLength)
{
if(!doneonce)
{
buffdata = new byte[ulLength];
Marshal.Copy(pbdata, buffdata, 0, 8600);
}
IntPtr phrawFile = pvCallbackContext;
int i = ReadFile(phrawFile, buffdata,ulLength,ref nBytesRead,IntPtr.Zero);
if(i == 0)
{
Console.WriteLine("Read File Failed with {0}", Marshal.GetLastWin32Error());
}
ulLength = nBytesRead;
nTotalBytes+=nBytesRead;
Console.WriteLine("Total Bytes Read are : " + nTotalBytes);
doneonce = true;
return 0;
}
Mattias Sjögren - 09 Nov 2005 09:36 GMT
> private delegate int ImportCallBack(IntPtr pbdata,IntPtr
> pvCallbackContext,int ulLength);
ulLength should be a ref parameter.
Mattias