Why does this code get an access error on the Result := Buffer line in D2010, but not D7?
Something, I'd guess, involving UniCode, but the compiler doesn't generate any warnings.
Any suggestions on an elegant workaround?
Edit: Ouch: the GetTempPath call is trashing the stack as evidenced by the fact that Extension is empty after the GetTempPath line, but not before... Yikes.
function GetTempPathAndFileName( const Extension: string): string;
var
Buffer: array[0..MAX_PATH] of Char;
begin
repeat
GetTempPath(SizeOf(Buffer) - 1, Buffer);
GetTempFileName(Buffer, '~', 0, Buffer);
Result := Buffer; // <--- crashes on this line,
Result := ChangeFileExt(Result, Extension);
until not FileExists(Result);
end; { GetTempPathAndFileName }
GetTempPath is expecting the number of chars in the buffer for its first argument, not the size in bytes. Change SizeOf
to Length
and it will work.
To make it work as in D7, replace "string" with "AnsiString" and "Char" with "AnsiChar". Also, call GetTempPathA and GetTempFileNameA rather than GetTempPath and GetTempFileName.
But the approach given by Mason is probably better, for it will support Unicode file names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With