Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   OOP (https://www.clubdelphi.com/foros/forumdisplay.php?f=5)
-   -   Como tratar un archivo cuyo nombre tiene espacios en blanco (https://www.clubdelphi.com/foros/showthread.php?t=83212)

darkamerico 22-05-2013 20:18:23

Como tratar un archivo cuyo nombre tiene espacios en blanco
 
Hola nuevamente estimados amigos, verán, estoy realizando una aplicacion de manejo de documentos, y en uno de sus modulos doy la capacidad de subir archivos locales a un FTP Server, todo va vien con rutas que no contienen espacios en blanco, pero el programa arroja una excepcion externa en otro caso.

El codigo que estoy usando es el siguiente:

Código Delphi [-]
var
 Tam,FHandle,BytesEnviados, idDoc : integer;
begin
    FHandle := FileOpen(archivox, 0);
    Tam := Getfilesize(FHandle,nil);
    FileClose(FHandle);

Ahi la variable Tam arroja -1 cuando archivox contiene espacios en blanco.

Agradezco su ayuda

Americo

escafandra 22-05-2013 21:40:55

Encierra el nombre de archivo entre comillas.


Un saludo.

darkamerico 22-05-2013 22:31:54

Saludos
 
Hola, hice lo que me dijiste pero tampoco funcionó, mira colocaré a continuacion los bloques del código:

Código Delphi [-]
...
var
  Form5: TForm5;
  archivox, rutaEmisor, rutaSelecc:string;
  idEmisor, idTipDoc:integer;
...
procedure TForm5.btnExaminarClick(Sender: TObject);
begin
  if open.Execute then
  begin
      archivox:=open.FileName;
      archivox:=chr(39) + archivox + chr(39);
      lblFilename.Caption:=archivox;
      btnGrabar.Enabled:=true;
      btnGrabar.SetFocus;
  end;
end;

procedure TForm5.btnGrabarClick(Sender: TObject);
var
 Tam,FHandle,BytesEnviados, idDoc : integer;
begin
    FHandle := FileOpen(archivox, 0);
    Tam := Getfilesize(FHandle,nil);
    FileClose(FHandle);
    ...
end;
...

Haber si alguien ve que está sucediendo :(

Saludos

Casimiro Noteví 22-05-2013 23:28:27

Prueba con
Código Delphi [-]
archivox := QuotedStr( archivox );

darkamerico 22-05-2013 23:39:36

Toda la Unidad
 
Amigo, no funciona, aqui coloco toda la unidad:

Código Delphi [-]
unit Unit5;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, StdCtrls, ComCtrls, TabNotBk, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdFTP, DBCtrls,
  Grids, DBGrids, ShellAPI, Mask, StrUtils;

type
  TForm5 = class(TForm)
    TabbedNotebook1: TTabbedNotebook;
    Panel1: TPanel;
    Label1: TLabel;
    Label2: TLabel;
    cboEmisor: TComboBox;
    Panel2: TPanel;
    Label3: TLabel;
    Label4: TLabel;
    cboEmisora: TComboBox;
    Label5: TLabel;
    cboTipDoc: TComboBox;
    Label6: TLabel;
    txtTitulo: TMemo;
    Label7: TLabel;
    cboFechaPub: TDateTimePicker;
    btnExaminar: TButton;
    Label8: TLabel;
    btnGrabar: TButton;
    open: TOpenDialog;
    lblFilename: TLabel;
    clienteFTP: TIdFTP;
    ProgressBar1: TProgressBar;
    gridFilesXEntidad: TDBGrid;
    DBNavigator1: TDBNavigator;
    Panel3: TPanel;
    Label9: TLabel;
    Label10: TLabel;
    Label11: TLabel;
    Label12: TLabel;
    Label13: TLabel;
    Button1: TButton;
    DBEdit1: TDBEdit;
    DBEdit2: TDBEdit;
    DBMemo1: TDBMemo;
    DBEdit3: TDBEdit;
    procedure FormActivate(Sender: TObject);
    procedure btnExaminarClick(Sender: TObject);
    procedure cboEmisoraChange(Sender: TObject);
    procedure btnGrabarClick(Sender: TObject);
    procedure cboTipDocChange(Sender: TObject);
    procedure clienteFTPWork(ASender: TObject; AWorkMode: TWorkMode;
      AWorkCount: Int64);
    procedure cboEmisorChange(Sender: TObject);
    procedure gridFilesXEntidadCellClick(Column: TColumn);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form5: TForm5;
  archivox, rutaEmisor, rutaSelecc:string;
  idEmisor, idTipDoc:integer;

implementation

uses DM;

{$R *.dfm}

procedure OpenFileInOSShell(AFile: string);
begin
  //ShellExecute(0, 'open', PChar(AFile), nil, nil, SW_SHOW);
  ShellExecute(0, 'open', PChar(AFile), PChar('"' + AFile + '"'), nil, SW_SHOW);
end;

procedure TForm5.btnExaminarClick(Sender: TObject);
begin
  if open.Execute then
  begin
      archivox:=QuotedStr(open.FileName);
      lblFilename.Caption:=archivox;
      btnGrabar.Enabled:=true;
      btnGrabar.SetFocus;
  end;
end;

procedure TForm5.btnGrabarClick(Sender: TObject);
var
 Tam,FHandle,BytesEnviados, idDoc : integer;
begin
    FHandle := FileOpen(archivox, 0);
    Tam := Getfilesize(FHandle,nil);
    FileClose(FHandle);
    //******** Conecto con servidor Ftp
    ClienteFTP.Username := 'magus';
    ClienteFTP.Password := 'magussersa';
    ClienteFTP.Host := '192.168.1.215';

    Try
      ClienteFTP.Connect ;
    Except
      Showmessage ('Error en la Conexion con el Servidor FTP');
    End;

    If ClienteFTP.Connected then
    Begin
      ProgressBar1.Min := 0;
      ProgressBar1.Max := Tam;
      ClienteFTP.BeginWork(wmWrite);

      Try
        ClienteFTP.Put(archivox,rutaEmisor+'/'+ExtractFileName(archivox));
        ClienteFTP.EndWork(wmWrite);
        ClienteFTP.Disconnect;
        Finally
          BytesEnviados := ProgressBar1.Position;

          If BytesEnviados < Tam then
            ShowMessage('El Archivo no pudo ser Enviado')
          Else
          begin
            ShowMessage('El Archivo fue Enviado corréctamente');
            // Insertar el registro
            dmBanco.q_CalcIDDoc.close;
            dmBanco.q_CalcIDDoc.Open;

            if length(dmBanco.q_CalcIDDoc.FieldByName('idDoc').AsString)=0 then
              idDoc:=1
            else
              idDoc:=dmBanco.q_CalcIDDoc.FieldByName('idDoc').AsInteger;

            dmBanco.q_INSDoc.Close;
            dmBanco.q_INSDoc.Params[0].AsInteger:=idDoc;
            dmBanco.q_INSDoc.Params[1].AsInteger:=idEmisor;
            dmBanco.q_INSDoc.Params[2].AsInteger:=idTipDoc;
            dmBanco.q_INSDoc.Params[3].AsString:=trim(txtTitulo.Text);
            dmBanco.q_INSDoc.Params[4].AsString:=DateToStr(cboFechaPub.Date);
            dmBanco.q_INSDoc.Params[5].AsString:='./'+rutaEmisor+'/'+ExtractFileName(archivox);
            dmBanco.q_INSDoc.ExecSQL;
          end;
          End;
      End;
      btnGrabar.Enabled:=false;
      cboEmisora.Text:='Seleccionar...';
      cboTipDoc.Text:='Seleccionar...';
      txtTitulo.Text:='';
      cboFechaPub.Date:=date;
      lblFilename.Caption:='';
      progressbar1.Position:=0;
end;

procedure TForm5.Button1Click(Sender: TObject);
begin
  OpenFileInOSShell('ftp://magus:[email protected]/' + rutaSelecc);
end;

procedure TForm5.cboEmisoraChange(Sender: TObject);
var
  posPunto:integer;
begin
  if(cboEmisora.Text<>'Seleccionar...')then
  begin
    posPunto:=pos('.',cboEmisora.Text);
    dmBanco.q_RutaDeEmisor.Close;
    dmBanco.q_RutaDeEmisor.Params[0].AsInteger:=StrToInt(copy(cboEmisora.Text,1,posPunto-1));
    dmBanco.q_RutaDeEmisor.Open;
    rutaEmisor:=dmBanco.q_RutaDeEmisor.FieldByName('carpeta').AsString;
    idEmisor:=StrToInt(copy(cboEmisora.Text,1,posPunto-1));
  end;
end;

procedure TForm5.cboEmisorChange(Sender: TObject);
var
  posPunto:integer;
begin
  if cboEmisor.Text<>'Seleccionar...' then
  begin
    posPunto:=pos('.',cboEmisor.text);
    dmBanco.q_GridFilesXEntidad.Close;
    dmBanco.q_GridFilesXEntidad.Params[0].AsInteger:=StrToInt(copy(cboEmisor.Text,1,posPunto-1));
    dmBanco.q_GridFilesXEntidad.Open;
    dmBanco.q_GridFilesXEntidad.Active:=true;
  end;
end;

procedure TForm5.cboTipDocChange(Sender: TObject);
var
  posPunto:integer;
begin
  if(cboTipDoc.Text<>'Seleccionar...') then
  begin
    posPunto:=pos('.',cboTipDoc.Text);
    idTipDoc:=StrToInt(copy(cboTipDoc.Text,1,posPunto-1));
  end;
end;

procedure TForm5.clienteFTPWork(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCount: Int64);
begin
  ProgressBar1.Position := AWorkCount;
end;

procedure TForm5.FormActivate(Sender: TObject);
begin
  cbofechaPub.Date:=date;

  cboEmisora.Items.Clear;
  cboEmisor.Items.Clear;
  dmBanco.q_Emisoras.Close;
  dmBanco.q_Emisoras.Open;
  while not dmBanco.q_Emisoras.Eof do
  begin
    cboEmisor.Items.Add(dmBanco.q_Emisoras.FieldByName('idemisor').AsString + '.' + dmBanco.q_Emisoras.FieldByName('emisor').AsString);
    cboEmisora.Items.Add(dmBanco.q_Emisoras.FieldByName('idemisor').AsString + '.' + dmBanco.q_Emisoras.FieldByName('emisor').AsString);
    dmBanco.q_Emisoras.Next;
  end;
  dmBanco.q_Emisoras.Close;

  cboTipDoc.Items.Clear;
  dmBanco.q_TipDoc.Close;
  dmBanco.q_TipDoc.Open;
  while not dmBanco.q_TipDoc.Eof do
  begin
    cboTipDoc.Items.Add(dmBanco.q_TipDoc.FieldByName('idtipdoc').AsString + '.' + dmBanco.q_TipDoc.FieldByName('tipdoc').AsString);
    dmBanco.q_TipDoc.Next;
  end;
  dmBanco.q_TipDoc.Close;
end;

procedure TForm5.gridFilesXEntidadCellClick(Column: TColumn);
begin
  rutaSelecc:=gridFilesXEntidad.DataSource.DataSet.Fields[4].AsString;
end;

end.

Neftali [Germán.Estévez] 23-05-2013 11:00:01

Pues yo no acabo de reproducir el problema. O lo estoy haciendo mal o se me escapa algo.
¿Sistema? ¿Versión de Delphi? ....

Pruebo el primer código que has puesto con un fichero con espacio y me da bien.



Nombre con espacios. Al obtener el tamaño me da correcto.



:confused:

Neftali [Germán.Estévez] 23-05-2013 11:06:39

Lo he probado con delphi 6 y correcto también.
No debo estar entendiendo algo... :(

ecfisa 23-05-2013 12:26:03

Hola.

Hice una prueba en Delphi 7 y también funciona correctamente habiendo espacios en el nombre.
Código Delphi [-]
procedure TForm1.Button1Click(Sender: TObject);
var
  archivox : string;
  FHandle  : integer;
  Tam      : DWORD;
begin
  archivox := 'C:\TR 2013 04.txt';
  FHandle  := FileOpen(archivox, fmOpenRead);
  Tam      := GetFileSize(FHandle, nil);
  FileClose(FHandle);
  ShowMessage(Format('Name: %s %sSize: %d', [archivox, #10, Tam]));
end;

Saludos.

darkamerico 23-05-2013 18:10:54

Amigos
 
En primer lugar deseo agradecer la atención que han tenido con este post, en un inicio pense que el error era debido a que la ruta tenia espacios en blanco, pero me percate luego que arrojaba error cuando keria ver un archivo que tenia abierto, por eso integre en el proyecto una validación para evitar que el archivo fuera visualizado si estaba abierto, y al parecer las cosas funcionaron!

Aqui les dejo la unidad completa nuevamente para quien desee verla. Se aceptan por supuesto recomendaciones de mejorar lo que aqui se presenta:

Código Delphi [-]
unit Unit5;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, StdCtrls, ComCtrls, TabNotBk, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdFTP, DBCtrls,
  Grids, DBGrids, ShellAPI, Mask, StrUtils;

type
  TForm5 = class(TForm)
    tabs: TTabbedNotebook;
    Panel1: TPanel;
    Label1: TLabel;
    Label2: TLabel;
    cboEmisor: TComboBox;
    Panel2: TPanel;
    Label3: TLabel;
    Label4: TLabel;
    cboEmisora: TComboBox;
    Label5: TLabel;
    cboTipDoc: TComboBox;
    Label6: TLabel;
    txtTitulo: TMemo;
    Label7: TLabel;
    cboFechaPub: TDateTimePicker;
    btnExaminar: TButton;
    Label8: TLabel;
    btnGrabar: TButton;
    open: TOpenDialog;
    lblFilename: TLabel;
    clienteFTP: TIdFTP;
    ProgressBar1: TProgressBar;
    gridFilesXEntidad: TDBGrid;
    DBNavigator1: TDBNavigator;
    Panel3: TPanel;
    Label9: TLabel;
    Label10: TLabel;
    Label11: TLabel;
    Label12: TLabel;
    Label13: TLabel;
    btnVisualizar: TButton;
    DBEdit1: TDBEdit;
    DBEdit2: TDBEdit;
    DBMemo1: TDBMemo;
    DBEdit3: TDBEdit;
    procedure FormActivate(Sender: TObject);
    procedure btnExaminarClick(Sender: TObject);
    procedure cboEmisoraChange(Sender: TObject);
    procedure btnGrabarClick(Sender: TObject);
    procedure cboTipDocChange(Sender: TObject);
    procedure clienteFTPWork(ASender: TObject; AWorkMode: TWorkMode;
      AWorkCount: Int64);
    procedure cboEmisorChange(Sender: TObject);
    procedure gridFilesXEntidadCellClick(Column: TColumn);
    procedure btnVisualizarClick(Sender: TObject);
    procedure tabsChange(Sender: TObject; NewTab: Integer;
      var AllowChange: Boolean);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form5: TForm5;
  archivox, rutaEmisor, rutaSelecc:string;
  idEmisor, idTipDoc:integer;

implementation

uses DM;

{$R *.dfm}

procedure OpenFileInOSShell(AFile: string);
begin
  //ShellExecute(0, 'open', PChar(AFile), nil, nil, SW_SHOW);
  ShellExecute(0, 'open', PChar(AFile), PChar('"' + AFile + '"'), nil, SW_SHOW);
end;

procedure TForm5.btnExaminarClick(Sender: TObject);
begin
  if open.Execute then
  begin
      archivox:=open.FileName;
      lblFilename.Caption:=archivox;
      btnGrabar.Enabled:=true;
      btnGrabar.SetFocus;
  end;
end;

procedure TForm5.btnGrabarClick(Sender: TObject);
var
 Tam,FHandle,BytesEnviados, idDoc : integer;
 TmpFile:TFileStream;
begin
  try
    TmpFile:= TFileStream.create(archivox, fmOpenRead or fmShareExclusive);
    TmpFile.free;
    FHandle := FileOpen(archivox, 0);
    Tam := Getfilesize(FHandle,nil);
    FileClose(FHandle);
    //******** Conecto con servidor Ftp
    ClienteFTP.Username := 'magus';
    ClienteFTP.Password := 'magussersa';
    ClienteFTP.Host := '192.168.1.215';
    Try
      ClienteFTP.Connect ;
    Except
      Showmessage ('Error en la Conexion con el Servidor FTP');
    End;

    If ClienteFTP.Connected then
    Begin
      ProgressBar1.Min := 0;
      ProgressBar1.Max := Tam;
      ClienteFTP.BeginWork(wmWrite);

      Try
        ClienteFTP.Put(archivox,rutaEmisor+'/'+ExtractFileName(archivox));
        ClienteFTP.EndWork(wmWrite);
        ClienteFTP.Disconnect;
        Finally
          BytesEnviados := ProgressBar1.Position;

          If BytesEnviados < Tam then
            ShowMessage('El Archivo no pudo ser Enviado')
          Else
          begin
            ShowMessage('El Archivo fue Enviado corréctamente');
            // Insertar el registro
            dmBanco.q_CalcIDDoc.close;
            dmBanco.q_CalcIDDoc.Open;

            if length(dmBanco.q_CalcIDDoc.FieldByName('idDoc').AsString)=0 then
              idDoc:=1
            else
              idDoc:=dmBanco.q_CalcIDDoc.FieldByName('idDoc').AsInteger;

            dmBanco.q_INSDoc.Close;
            dmBanco.q_INSDoc.Params[0].AsInteger:=idDoc;
            dmBanco.q_INSDoc.Params[1].AsInteger:=idEmisor;
            dmBanco.q_INSDoc.Params[2].AsInteger:=idTipDoc;
            dmBanco.q_INSDoc.Params[3].AsString:=trim(txtTitulo.Text);
            dmBanco.q_INSDoc.Params[4].AsString:=DateToStr(cboFechaPub.Date);
            dmBanco.q_INSDoc.Params[5].AsString:='./'+rutaEmisor+'/'+ExtractFileName(archivox);
            dmBanco.q_INSDoc.ExecSQL;
          end;
          End;
      End;
      btnGrabar.Enabled:=false;
      cboEmisora.Text:='Seleccionar...';
      cboTipDoc.Text:='Seleccionar...';
      txtTitulo.Text:='';
      cboFechaPub.Date:=date;
      lblFilename.Caption:='';
      progressbar1.Position:=0;
  except
    ShowMessage('Cierre el archivo antes de realizar la operacion');
  end;

end;

procedure TForm5.btnVisualizarClick(Sender: TObject);
begin
  OpenFileInOSShell('ftp://magus:[email protected]/' + rutaSelecc);
  btnVisualizar.Enabled:=false;
end;

procedure TForm5.cboEmisoraChange(Sender: TObject);
var
  posPunto:integer;
begin
  if(cboEmisora.Text<>'Seleccionar...')then
  begin
    posPunto:=pos('.',cboEmisora.Text);
    dmBanco.q_RutaDeEmisor.Close;
    dmBanco.q_RutaDeEmisor.Params[0].AsInteger:=StrToInt(copy(cboEmisora.Text,1,posPunto-1));
    dmBanco.q_RutaDeEmisor.Open;
    rutaEmisor:=dmBanco.q_RutaDeEmisor.FieldByName('carpeta').AsString;
    idEmisor:=StrToInt(copy(cboEmisora.Text,1,posPunto-1));
  end;
end;

procedure TForm5.cboEmisorChange(Sender: TObject);
var
  posPunto:integer;
begin
  if cboEmisor.Text<>'Seleccionar...' then
  begin
    posPunto:=pos('.',cboEmisor.text);
    dmBanco.q_GridFilesXEntidad.Close;
    dmBanco.q_GridFilesXEntidad.Params[0].AsInteger:=StrToInt(copy(cboEmisor.Text,1,posPunto-1));
    dmBanco.q_GridFilesXEntidad.Open;
    dmBanco.q_GridFilesXEntidad.Active:=true;
    btnVisualizar.Enabled:=false;
  end;
end;

procedure TForm5.cboTipDocChange(Sender: TObject);
var
  posPunto:integer;
begin
  if(cboTipDoc.Text<>'Seleccionar...') then
  begin
    posPunto:=pos('.',cboTipDoc.Text);
    idTipDoc:=StrToInt(copy(cboTipDoc.Text,1,posPunto-1));
  end;
end;

procedure TForm5.clienteFTPWork(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCount: Int64);
begin
  ProgressBar1.Position := AWorkCount;
end;

procedure TForm5.FormActivate(Sender: TObject);
begin
  tabs.PageIndex:=0;
  cbofechaPub.Date:=date;

  cboEmisora.Items.Clear;
  cboEmisor.Items.Clear;
  dmBanco.q_Emisoras.Close;
  dmBanco.q_Emisoras.Open;
  while not dmBanco.q_Emisoras.Eof do
  begin
    cboEmisor.Items.Add(dmBanco.q_Emisoras.FieldByName('idemisor').AsString + '.' + dmBanco.q_Emisoras.FieldByName('emisor').AsString);
    cboEmisora.Items.Add(dmBanco.q_Emisoras.FieldByName('idemisor').AsString + '.' + dmBanco.q_Emisoras.FieldByName('emisor').AsString);
    dmBanco.q_Emisoras.Next;
  end;
  dmBanco.q_Emisoras.Close;

  cboTipDoc.Items.Clear;
  dmBanco.q_TipDoc.Close;
  dmBanco.q_TipDoc.Open;
  while not dmBanco.q_TipDoc.Eof do
  begin
    cboTipDoc.Items.Add(dmBanco.q_TipDoc.FieldByName('idtipdoc').AsString + '.' + dmBanco.q_TipDoc.FieldByName('tipdoc').AsString);
    dmBanco.q_TipDoc.Next;
  end;
  dmBanco.q_TipDoc.Close;
end;

procedure TForm5.gridFilesXEntidadCellClick(Column: TColumn);
begin
  rutaSelecc:=gridFilesXEntidad.DataSource.DataSet.Fields[4].AsString;
  btnVisualizar.Enabled:=true;
end;

procedure TForm5.tabsChange(Sender: TObject; NewTab: Integer;
  var AllowChange: Boolean);
begin
  btnVisualizar.Enabled:=false;
end;

end.


La franja horaria es GMT +2. Ahora son las 07:57:20.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi