将记录保存到文件错误'文件访问被拒绝'

时间:2014-10-27 15:24:17

标签: delphi

当我运行我的代码时,选择我创建的保存按钮。记录没有保存,但我收到错误'文件访问被拒绝'。

我的代码:

我将代码拆分为2个单元MainUnit和AddTenantUnit。

我认为问题在于代码末尾的过程。如果向下滚动,我会清楚说明哪个程序(TAddTenantForm.SaveButtonClick)。

unit MainUnit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TMainForm = class(TForm)
    AddTenantButton: TButton;
    procedure FormCreate(Sender: TObject);
    procedure AddTenantButtonClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
  TTenantRecord = record
    FirstName : string[20];
    LastName : string[20];
  end;

var
  MainForm: TMainForm;
  Tenant : TTenantRecord;
  TenantFile : file of TTenantRecord;

implementation

uses AddTenantUnit;

{$R *.dfm}

procedure TMainForm.AddTenantButtonClick(Sender: TObject);
begin
  AddTenantForm.ShowModal;
end;

procedure TMainForm.FormCreate(Sender: TObject);
begin
  assignfile (TenantFile, 'Tenant.dat');
  if not fileexists ('Tenant.dat')
  then
    begin
      rewrite (TenantFile);
      closefile (TenantFile)
    end
  {endif};
end;

end.


unit AddTenantUnit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, MainUnit, StdCtrls;

type
  TAddTenantForm = class(TForm)
    MainFormButton: TButton;
    FirstNameLabel: TLabel;
    FirstNameEdit: TEdit;
    LastNameLabel: TLabel;
    LastNameEdit: TEdit;
    SaveButton: TButton;
    ClearButton: TButton;
    procedure SaveButtonClick(Sender: TObject);
    procedure LastNameEditChange(Sender: TObject);
    procedure ClearButtonClick(Sender: TObject);
    procedure FirstNameEditChange(Sender: TObject);
    procedure MainFormButtonClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  AddTenantForm: TAddTenantForm;

implementation

{$R *.dfm}

procedure TAddTenantForm.MainFormButtonClick(Sender: TObject);
begin
  AddTenantForm.Close;
end;

procedure TAddTenantForm.FirstNameEditChange(Sender: TObject);
begin
  Tenant.FirstName := FirstNameEdit.Text;
end;

procedure TAddTenantForm.ClearButtonClick(Sender: TObject);
begin
  FirstNameEdit.Clear;
  LastNameEdit.Clear;
end;

procedure TAddTenantForm.LastNameEditChange(Sender: TObject);
begin
  Tenant.LastName := LastNameEdit.Text;
end;

// This is where the problem lies when I run this piece of
// code. This represents the Save button being clicked.
procedure TAddTenantForm.SaveButtonClick(Sender: TObject);
begin
  assignfile (TenantFile, 'Tenant.dat');
  write(TenantFile, Tenant);
  closefile (TenantFile);
end;


end.

1 个答案:

答案 0 :(得分:2)

您正在尝试将数据写入未打开的文件中。

procedure TAddTenantForm.SaveButtonClick(Sender: TObject);
begin
  assignfile (TenantFile, 'Tenant.dat');
  // Rewrite(TenantFile) or Reset(TenantFile) missed here
  write(TenantFile, Tenant);
  closefile (TenantFile);
end;
相关问题