Error:the filename directory name or volume label syntax is incorrect, in Delphi 7 CopyFile Function

StackOverflow https://stackoverflow.com/questions/4848861

I want to copy files from one folder to another using CopyFile function. The source files paths are stored in a ClientDataSet called "itemsDB". The code is :

Var Source, Dest : String;
Begin
  itemsDB.First;
  While Not itemsDB.EOF do
  Begin
    Source := itemsDB.FieldValues['FileN'];
    Dest := 'C:\NewDir\'+ExtractFileName(Source);
    if Not CopyFile(PChar(Source), PChar(Dest), False) then
          Showmessage(SysErrorMessage(getlasterror()));
     itemsDB.Next;
  end; 
 end

When I execute the code, I get the error message "the filename directory name or volume label syntax is incorrect". I verfied all the files paths in the DataSet, they're correct. In my example, my clientdataset contains two JPG images "c:\test1.jpg" and "c:\test2.jpg" When I tried source := 'c:\test1.jpg', it works perfectly, but when I get it from the clientdataset, it fails.

Thanks in advance

有帮助吗?

解决方案

Updated answer...

(As recommended...)

After some discussion in the comments field, the error was discovered to be invalid trailing space characters in the Source string.

If the FileN field is defined as a FixedChar string field, the Source will include these trailing spaces.

Set FixedChar to False in the object inspector, or remove the trailing space characters with Source := Trim(Source);

其他提示

Could you log the values of FileName and Dest to see exactly what is being passed to CopyFile?

Also, it looks like you are not using Source but rather FileName, which doesn't appear to be defined anywhere in the code fragment you posted. Did you mean to use Source?

You will get this error if you have a : as a part of path in Source. You may have one of course like in c:\ but c:\Test:Folder\Text.txt will give you the error The filename, directory name, or volume label syntax is incorrect.

Edit 1 Another invalid character is ?. I do not know if you use Unicode in Delphi or if your source of data is Unicode but sometimes unknown Unicode characters gets translated to ?.

Edit 2 Spaces before the drive letter in source will also give you the same error.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top