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()
It’s recommended to use
GetFileSizeExinstead ofGetFileSize. But think yourCreateFilecall failed.CreateFiledoesn’t accept anHGLOBAL. And you’re converting the string to ANSI, then passing it to a Unicode version ofCreateFile, which is also broken.Just stay in Unicode, like this: