Ir para conteúdo
Fórum Script Brasil
  • 0

(Resolvido) Copiar tabela informando o caminho do executável


Gabriel Cabral

Pergunta

Preciso copiar a tabela ESTAPRO.dbf e colar na mesma pasta com o nome ESTAPROA.dbf

ambas deverão ficar na mesma pasta do executável.

Funcionou quando eu fiz da seguinte maneira:

DeleteFile('C:\winsuperm\ESTAPROA.DBF');
CopyFile('C:\winsuperm\ESTAPRO.DBF', 'C:\winsuperm\ESTAPROA.DBF', True);
Mas preciso indicar o caminho do executável, pois é diferente em cada cliente.. então fiz da seguinte maneira:
DeleteFile(PChar(ExtractFileDir(ParamStr(0))+'\ESTAPROA.DBF'));
CopyFile(PChar(ExtractFileDir(ParamStr(0))+'\ESTAPRO.DBF'), PChar(ExtractFileDir(ParamStr(0))+'\ESTAPROA.DBF'), True);

Só que desse jeito não funcionou.. não aconteceu nada...

E essa também foi a única maneira que eu encontrei para fazer uma cópia renomeada da tabela, a cada modificação nela.

alguém consegue me ajudar??

Muito obrigado.

Editado por Gabriel Cabral
Link para o comentário
Compartilhar em outros sites

18 respostass a esta questão

Posts Recomendados

  • 0

Uma forma possível, é a seguinte:

var
  NEW : String;
  OLD : String;
begin
  OLD := ExtractFileDir ( ParamStr ( 0 ) ) + '\ESTAPRO.DBF';
  NEW := ExtractFileDir ( ParamStr ( 0 ) ) + '\ESTAPROA.DBF';
  DeleteFile ( NEW );
  CopyFile ( PChar ( OLD ), PChar ( NEW ), True);
end;

Espero ter ajudado,

José Luiz.

Link para o comentário
Compartilhar em outros sites

  • 0

Veja primeiro se consegue encontrar o arquivo

procedure TForm1.Button2Click(Sender: TObject);
var
  buffer: array [0..255] of char;
  FileToFind: string;
begin
  GetWindowsDirectory(buffer, SizeOf(buffer));
  FileToFind := FileSearch(Edit1.Text, ExtractFilePath(Application.ExeName) + ';' + buffer);
  if FileToFind = '' then
    ShowMessage('Não Econtrado ' + Edit1.Text + '.')
  else
    ShowMessage('Encontrado ' + FileToFind + '.');

end;

Se conseguir encontrar o arquivo procurado, então fica mais facil montar a sua rotina

abraço

Link para o comentário
Compartilhar em outros sites

  • 0

Os arquivos foram encontrados, tanto ESTAPRO.DBF quanto ESTAPROA.DBF

Mas ainda assim a deleção e cópia não estao sendo feitas :(

Eu fiz um teste com arquivos texto e funcionou perfeitamente.

DeleteFile(PChar(ExtractFileDir(ParamStr(0))+'\b.txt'));
CopyFile(PChar(ExtractFileDir(ParamStr(0))+'\a.txt'), PChar(ExtractFileDir(ParamStr(0))+'\b.txt'), True);

por que será, então, que com as tabelas .DBF isso não funciona???

Não funciona agora, porque quando eu informava o caminho exatamente com c:\... funcionava também

Link para o comentário
Compartilhar em outros sites

  • 0

Coloquei isso, mas ainda não funciona..

procedure TfrmCadPro.Button1Click(Sender: TObject);
var
  buffer: array [0..255] of char;
  FileToFind: string;
  FileToFindA: string;
begin

  dm.ESTAPRO.Active := False;
  dm.ESTAPROA.Active := False;

  GetWindowsDirectory(buffer, SizeOf(buffer));
  FileToFind := FileSearch('ESTAPRO.DBF', ExtractFilePath(Application.ExeName) + ';' + buffer);
  FileToFindA := FileSearch('ESTAPROA.DBF', ExtractFilePath(Application.ExeName) + ';' + buffer);

  DeleteFile(PChar(ExtractFilePath(ParamStr(0)) + FileToFindA));
  CopyFile(PChar(ExtractFilePath(ParamStr(0)) + FileToFind), PChar(ExtractFilePath(ParamStr(0)) + FileToFindA), True);

end;

Experimentei usar .Close; também, mas também não deu certo

Link para o comentário
Compartilhar em outros sites

  • 0

experimente esse exemplo

procedure TForm1.Button1Click(Sender: TObject);
var
  buffer: array [0..255] of char;
  FileToFind: string;
  FileToFindA: string;
begin
  GetWindowsDirectory(buffer, SizeOf(buffer));

  FileToFind := FileSearch(Edit1.Text, 'C:\' + ';' + buffer);

  if FileToFind = '' then
    ShowMessage('Não Econtrado ' + Edit1.Text + '.')
  else
    begin
      ShowMessage('Encontrado ' + FileToFind + '.');
      DeleteFile(PChar(FileToFind));
    end;

  FileToFindA := FileSearch(Edit2.Text, 'C:\' + ';' + buffer);

  if FileToFindA = '' then
    ShowMessage('Não Econtrado ' + Edit2.Text + '.')
  else
    begin
      ShowMessage('Encontrado ' + FileToFindA + '.');
      CopyFile(PChar(FileToFindA), PChar(FileToFindA+'X'), True);
    end;

end;

OBS: quando não funciona é porque o caminho do arquivo não foi encontrado

abraço

Link para o comentário
Compartilhar em outros sites

  • 0

Fiz o teste em 3 diretórios diferentes, e em rede.

Todos funcionaram.

No meu teste, tanto o arquivo a ser copiado quanto o executável estavam no mesmo diretório.

Se este é o seu caso, esta forma funciona com certeza.

José Luiz.

Em tempo,

Já tive problema para copiar um arquivo depois que ele foi aberto, mesmo dando o comando Close.

Procure fazer a cópia antes de abrir o arquivo.

Link para o comentário
Compartilhar em outros sites

  • 0

Mas preciso fazer essa cópia após cada modificação na tabela...

ma falaram para usar o BatchMove... alguém conhece???

Eu informei ESTAPRO.DBF como Origem e ESTAPROA.DBF como Destino.

Mas não sei exatamente o modo que tenho que utilizar...

batAppend não é, pois esse duplica tudo.... mas é o único q funciona até agora...

batAppendUpdate dá um erro dizendo: Destination must be indexed. Table.

Não sei exatamente o que está havendo...

Link para o comentário
Compartilhar em outros sites

  • 0

Coloquei desta forma, e o Mode está batAppendUpdate...

dm.ESTAPRO.Post;

dm.ESTAPRO.Active := False;
dm.ESTAPRO.Exclusive := True;

dm.ESTAPROA.Active := False;
dm.ESTAPROA.Exclusive := True;

frmCadPro.BatchMove1.Execute;

Mas está dando a mensagem: Table is busy.

Editado por Gabriel Cabral
Link para o comentário
Compartilhar em outros sites

  • 0

Mas está dando a mensagem: Table is busy.

Menssagem : Tabela em Uso

eu não posso colocar c:\ porque em alguns clientes, o programa não está instalado no c:\

Eu coloquei c:\ para mostrar a voce, que se, os arquivos não estiverem no caminho do executavel, voce terá que procurá-los primeiro e informar o caminho onde eles foram achados. ( Tem que construir uma rotina para procurar como é feita pelo windows )

Acho que o componente TFindFile vai te ajudar

http://delphi.about.com/od/vclwriteenhance/a/tfindfile.htm

exemplo usando o componente

uses FindFile;
...
procedure TfrMain.Button2Click(Sender: TObject);
var FFile : TFindFile;
begin
  FFile := TFindFile.Create(nil);
  try
   FFile.FileAttr := [ffaAnyFile];
   FFile.InSubFolders := True;
   FFile.Path := ExtractFilePath(ParamStr(0));
   FFIle.FileMask := '*.pas';

   Memo1.Lines := FFile.SearchForFiles;
  finally
   FFile.Free;
  end;
end;
exemplo completo Download do componente http://delphi.about.com/library/tfindfile.zip http://www.delphiarea.com/?dl_id=8
{Article: TFindFile - Delphi Component
Tired of using FindFirst, Next and Close?
Come see how to encapsulate all those functions
in a single "find-files-recursively" component.
It's easy to use, free and with code.


For the .pas file of this component click here.
}

unit FindFile;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, FileCtrl;

type
  TFileAttrKind = (ffaReadOnly, ffaHidden, ffaSysFile, ffaVolumeID, ffaDirectory, ffaArchive, ffaAnyFile);
  TFileAttr = set of TFileAttrKind;

  TFindFile = class(TComponent)
  private
    s : TStringList;

    fSubFolder : boolean;
    fAttr: TFileAttr;
    fPath : string;
    fFileMask : string;

    procedure SetPath(Value: string);
    procedure FileSearch(const inPath : string);
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

    function SearchForFiles: TStringList;
  published
    property FileAttr: TFileAttr read fAttr write fAttr;
    property InSubFolders : boolean read fSubFolder write fSubFolder;
    property Path : string read fPath write SetPath;
    property FileMask : string read fFileMask write fFileMask;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('About.com', [TFindFile]);
end;

constructor TFindFile.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  Path := IncludeTrailingBackslash(GetCurrentDir); 
  FileMask := '*.*';
  FileAttr := [ffaAnyFile];
  s := TStringList.Create;
end;

destructor TFindFile.Destroy;
begin
  s.Free;
  inherited Destroy;
end;

procedure TFindFile.SetPath(Value: string);
begin
  if fPath <> Value then
  begin
    if Value <> '' then
      if DirectoryExists(Value) then
        fPath := IncludeTrailingBackslash(Value);
  end;
end;

function TFindFile.SearchForFiles: TStringList;
begin
  s.Clear;
  try
    FileSearch(Path);
  finally
    Result := s;
  end;
end;

procedure TFindFile.FileSearch(const InPath : string);
var Rec  : TSearchRec;
    Attr : integer;
begin
Attr := 0;
if ffaReadOnly in FileAttr then Attr := Attr + faReadOnly;
if ffaHidden in FileAttr then Attr := Attr + faHidden;
if ffaSysFile in FileAttr then Attr := Attr + faSysFile;
if ffaVolumeID in FileAttr then Attr := Attr + faVolumeID;
if ffaDirectory in FileAttr then Attr := Attr + faDirectory;
if ffaArchive in FileAttr then Attr := Attr + faArchive;
if ffaAnyFile in FileAttr then Attr := Attr + faAnyFile;

if SysUtils.FindFirst(inPath + FileMask, Attr, Rec) = 0 then
 try
   repeat
     s.Add(inPath + Rec.Name);
   until SysUtils.FindNext(Rec) <> 0;
 finally
   SysUtils.FindClose(Rec);
 end;

If not InSubFolders then Exit;

if SysUtils.FindFirst(inPath + '*.*', faDirectory, Rec) = 0 then
 try
   repeat
   if ((Rec.Attr and faDirectory) <> 0)  and (Rec.Name<>'.') and (Rec.Name<>'..') then
     begin
       FileSearch(IncludeTrailingBackslash(inPath + Rec.Name));
     end;
   until SysUtils.FindNext(Rec) <> 0;
 finally
   SysUtils.FindClose(Rec);
 end;
end; 

end.

{
********************************************
Zarko Gajic
About.com Guide to Delphi Programming
[url=http://delphi.about.com]http://delphi.about.com[/url]
email: delphi.guide@about.com
free newsletter: [url=http://delphi.about.com/library/blnewsletter.htm]http://delphi.about.com/library/blnewsletter.htm[/url]
forum: [url=http://forums.about.com/ab-delphi/start/]http://forums.about.com/ab-delphi/start/[/url]
********************************************

abraço

Link para o comentário
Compartilhar em outros sites

  • 0

Finalmente consegui..

DeleteFile(PChar(ExtractFilePath(Application.ExeName) + '\ESTAPROA.DBF'));

CopyFile(PChar(ExtractFilePath(Application.ExeName) + '\ESTAPRO.DBF'), PChar(ExtractFilePath(Application.ExeName) + 'ESTAPROA.DBF'), False);

Tem que ser False ao invés de True ali no terceiro parâmetro...pra poder sobrescrever.... não tinha percebido isso ¬¬

Mas me parece que surgiu uma outra questão aqui para copiar apenas alguns registros de uma tabela para outra...

Continuo aqui ou abro outro tópico??

Muito obrigado a todos pela ajuda ;D

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...