Windows: Как канонизировать файл в специальную папку?

Я хочу сохранить некоторые имена файлов для пользователя (например, последние файлы).

Давайте использовать шесть примеров файлов:

  • c:\Documents & Settings\Ian\My Documents\Budget.xls
  • c:\Documents & Settings\Ian\My Documents\My Pictures\Daughter's Winning Goal.jpg
  • c:\Documents & Settings\Ian\Application Data\uTorrent
  • c:\Documents & Settings\All Users\Application Data\Consonto\SpellcheckDictionary.dat
  • c:\Develop\readme.txt
  • c:\Program Files\Adobe\Reader\WhatsNew.txt

я сейчас жестко прописал путь к специальным папкам. Если пользователь перенаправляет свои папки, перемещается на другой компьютер или обновляет свою операционную систему, пути будут нарушены:

я хочу быть хорошим разработчиком и преобразовывать эти жестко запрограммированные абсолютные пути в относительные пути из соответствующих специальных папок:

  • %CSIDL_Personal%\Budget.xls
  • %CSIDL_MyPictures%\Daughter's Winning Goal.jpg
  • %CSIDL_AppData%\uTorrent
  • %CSIDL_Common_AppData%\Consonto\SpellcheckDictionary.dat
  • c:\Develop\readme.txt
  • %CSIDL_Program_Files%\Adobe\Reader\WhatsNew.txt

Трудность заключается в том, что для одного и того же файла может быть несколько представлений, например:

  • c:\Documents & Settings\Ian\My Documents\My Pictures\Daughter's Winning Goal.jpg
  • %CSIDL_Profile%\My Documents\My Pictures\Daughter's Winning Goal.jpg
  • %CSIDL_Personal%\My Pictures\Daughter's Winning Goal.jpg
  • %CSIDL_MyPictures%\Daughter's Winning Goal.jpg

Также обратите внимание, что в Windows XP мои изображения хранятся в My Documents:

%CSIDL_Profile%\My Documents
%CSIDL_Profile%\My Documents\My Pictures

Но на Vista/7 они отдельные:

%CSIDL_Profile%\Documents
%CSIDL_Profile%\Pictures

Примечание: я понимаю синтаксис %CSIDL_xxx%\filename.ext не является действительным; что Windows не будет расширять эти ключевые слова, как будто они являются строками среды. Я только использую это как способ задать этот вопрос. Внутренне я бы, очевидно, хранил предметы другим способом, возможно, как CSIDL родитель и хвост пути, например:

 CSIDL_Personal         \Budget.xls
 CSIDL_MyPictures       \Daughter's Winning Goal.jpg
 CSIDL_AppData          \uTorrent
 CSIDL_Common_AppData   \Consonto\SpellcheckDictionary.dat
 -1                     c:\Develop\readme.txt   (-1, since 0 is a valid csidl)
 CSIDL_Program_Files    \Adobe\Reader\WhatsNew.txt

Возникает вопрос, как максимально использовать пути относительно канонических специальных папок?


Я думаю:

void CanonicalizeSpecialPath(String path, ref CSLID cslid, ref String relativePath)
{
   return "todo";
}

Смотрите также

2 ответа

Решение

Я полагаю, вы могли бы выяснить, как CSIDL отображает пути (используя что-то вроде SHGetKnownFolderPath), создать их обратный словарь, затем проверить, соответствует ли начало пути, который вы хотите сохранить, любому из ключей в словаре, а затем удалить начало и сохранить CSIDL, который соответствует.

Не слишком элегантно, но работа должна быть выполнена.

function CanonicalizeSpecialPath(const path: string): string;
var
    s: string;
    BestPrefix: string;
    BestCSIDL: Integer;
    i: Integer;
begin
    BestPrefix := ''; //Start with no csidl being the one
    BestCSIDL := 0;

    //Iterate over the csidls i know about today for Windows XP.    
    for i := Low(csidls) to High(csidls) do
    begin
       //Get the path of this csidl. If the OS doesn't understand it, it returns blank
       s := GetSpecialFolderPath(0, i, False);
       if s = '' then
          Continue;

       //Don't do a string search unless this candidate is larger than what we have
       if (BestPrefix='') or (Length(s) > Length(BestPrefix)) then
       begin
          //The special path must be at the start of our string
          if Pos(s, Path) = 1 then //1=start
          begin
             //This is the best csidl we have so far
             BestPrefix := s;
             BestCSIDL := i;
          end;
       end;
    end;

    //If we found nothing useful, then return the original string
    if BestPrefix = '' then
    begin
       Result := Path;
       Exit;
    end;

    {
       Return the canonicalized path as pseudo-environment string, e.g.:

           %CSIDL_PERSONAL%\4th quarter.xls
    }
    Result := '%'+CsidlToStr(BestCSIDL)+'%'+Copy(Path, Length(BestPrefix)+1, MaxInt);
end;

И еще есть функция, которая "расширяет" ключевые слова специальной среды:

function ExpandSpecialPath(const path: string): string;
begin
   ...
end;

который расширяется:

%CSIDL_PERSONAL%\4th quarter.xls

в

\\RoamingProfileServ\Users\ian\My Documents\4th quarter.xls

Это делается путем поиска%xx% в начале строки и его расширения.

Другие вопросы по тегам