Moving a file

Posted by DannyMac on May 18, 2001

How would one go about moving a c:\MyFolder\File.txt to the next folder in alphabetical order. Therefore if there are three folders c:\ - MyFolder, AFolder, and ThisFolder, File.txt would be moved into c:\ThisFolder as T is the next in the alphabetical order of these three folders. Just to clarify, folder: c:\A c:\B c:\C File.txt in c:\A, would be moved to c:\B.

Regards, Danny.

Re: webmaster Guido on May 21, 2001

1. Extract the starting directory from the filepath.
2. Extract the "parent" of the starting directory.
3. Make a list of the subdirectories of the parent directory and sort the list alphabetically.
4. Look up the index (position) of the starting directory in the list.
5. Get the name of the next directory from the list.
6. Move the file from the starting directory to the next directory.

Below, I added some example code. Of course, in a real program you would check for errors: does the file exists, does the directory have a parent directory, is the starting directory not the last one of the list (or even the only one), and so on...
To try the example, drop the following components on a form: an edit box, a button and a listbox.

procedure TForm1.Button1Click(Sender: TObject);
var
  TheFile, StartDir, ParentDir, NextDir: string;
  SR: TSearchRec;
  ErrCode: integer;
  IxStartDir: integer;
begin
  ListBox1.Clear;
  StartDir := ExtractFileDir(Edit1.Text);
  ParentDir := ExtractFileDir(StartDir);
  if ParentDir[Length(ParentDir)] = '\' then
    System.Delete(ParentDir, Length(ParentDir), 1);
  ErrCode := FindFirst(ParentDir + '\*.*', faAnyFile, SR);
  while ErrCode = 0 do begin
    if ((SR.Attr and faDirectory) <> 0) and (SR.Name[1] <> '.') then
      ListBox1.Items.Add(ParentDir + '\' + SR.Name);
    ErrCode := FindNext(SR);
  end;
  FindClose(SR);
  ListBox1.Sorted := True;
  IxStartDir := ListBox1.Items.IndexOf(StartDir);
  NextDir := ListBox1.Items[IxStartDir + 1];
  ListBox1.ItemIndex := IxStartDir + 1; // visual check
  TheFile := ExtractFileName(Edit1.Text);
  MoveFile(PChar(Edit1.Text), PChar(NextDir + TheFile));
end;

The listbox shows you what is going on; this is always a good idea when testing code. Later, in the real application, you can use a TStringList to hold and so sort the directories.