Reputation: 12910
I started a new project with type of Windows Forms application, and I put two textboxes (textbox1 and textbox2) and a button. I used OpenFileDialog to select a file from the system and put it's path in textbox1, I put the following code for the button:
HANDLE hFile;
HANDLE hMap ;
LPVOID base;
hFile = ::CreateFile((LPCWSTR)Marshal::StringToHGlobalAnsi(this->textBox1->Text).ToPointer(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,0,OPEN_EXISTING , FILE_FLAG_SEQUENTIAL_SCAN, 0);
unsigned long sifi= ::GetFileSize(hFile,NULL);
if(hFile !=INVALID_HANDLE_VALUE){
hMap= ::CreateFileMapping(hFile, 0, PAGE_READONLY | SEC_COMMIT, 0, 0, 0);//create Mem mapping for the file in virtual memory
}
if( hMap!=NULL){
base = ::MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0);//load the mapped file into the RAM
}
this->textBox2->Text=sifi.ToString();
What I am trying to do with that code is to read the file path from textbox1 to use it for openning a file handle and then get the size of the file and put it into textbox2. The problem now is, textbox2 shows incorrect value of the file size. It seems always like 4294967295 for all files!
Edit:
Thanks guys, I have solved the problem. It was in the first parameter of CreateFile, it supposes to be:
(LPCWSTR)Marshal::StringToHGlobalUni(this->textBox1->Text).ToPointer()
Upvotes: 2
Views: 1037
Reputation: 283733
It's recommended to use GetFileSizeEx
instead of GetFileSize
. But think your CreateFile
call failed.
CreateFile
doesn't accept an HGLOBAL
. And you're converting the string to ANSI, then passing it to a Unicode version of CreateFile
, which is also broken.
Just stay in Unicode, like this:
pin_ptr<wchar_t> wszFilename = PtrToStringChars(textBox1->Text);
HANDLE hFile = ::CreateFileW(wszFilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,0,OPEN_EXISTING , FILE_FLAG_SEQUENTIAL_SCAN, 0);
if (hFile == 0 || hFile == INVALID_HANDLE_VALUE) throw gcnew Win32Exception();
Upvotes: 2
Reputation: 13087
The GetFileSize function is returing an error value.
Note that if the return value is INVALID_FILE_SIZE (0xffffffff), an application must call GetLastError to determine whether the function has succeeded or failed.
See the API docs on MSDN.
By the way, I think @David Heffernan has a point here.
Upvotes: 2