怎样判断文件是否已被打开?(50分)

  • 主题发起人 主题发起人 lifeforever
  • 开始时间 开始时间
L

lifeforever

Unregistered / Unconfirmed
GUEST, unregistred user!
&nbsp; &nbsp;我在程序中读写一个xml文件,如果该文件被我用IE或其他的xml的读写工具打开的话,<br>在程序中改写时,会报错。<br>&nbsp; &nbsp;
 
try<br>&nbsp; xmldocument.修改...<br>except<br>&nbsp; showmessage("文件无法修改")<br>end;
 
我只想知道有什么函数可以判断文件是否被已被打开!!!
 
有没有函数可以判断文件是否被打开我就不知道,但我想如果<br>用互斥对象来进行检查应该可以行得通,在这里我提供一个<br>程序给你,该程序是用于使程序只运行一次的<br>unit Unit1; <br>interface <br>uses <br>&nbsp; Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; <br><br>type <br>&nbsp; TForm1 = class(TForm) <br>&nbsp; private <br>&nbsp; &nbsp; { Private declarations } <br>&nbsp; public <br>&nbsp; &nbsp; { Public declarations } <br>&nbsp; end; <br><br>var <br>&nbsp; Form1: TForm1; <br>&nbsp; mHandle: THandle; <br>// 保存Mutex句柄 <br>&nbsp; PreviousInstanceWindow:HWND; <br>&nbsp; Project: string; <br>&nbsp; AppName:string; <br><br>implementation <br><br>{$R *.DFM} <br>initialization <br>&nbsp; Project := 'RunOnlyOnce_MyProject'; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<br>//此处定义自己的项目名称,作为要创建的互斥区名,最好有自己特点已防止重复 <br>&nbsp; mHandle := CreateMutex(nil, True, PChar(Project)); <br>&nbsp; // lpMutexAttributes设为nil,bInitialOwner设为True(即本程序拥有该互斥区) <br>&nbsp; if GetLastError = ERROR_ALREADY_EXISTS then <br>&nbsp; //该互斥区已存在则表明已有本程序的另一个实例在运行 <br>&nbsp; &nbsp;begin <br>&nbsp; showmessage('已经有该程序的一个实例在运行'); <br>&nbsp; &nbsp; AppName:=Application.Title; <br>&nbsp; &nbsp; //保存程序标题 <br>&nbsp; &nbsp; Application.ShowMainForm := false; <br>&nbsp; &nbsp; //不显示本窗口 <br>&nbsp; &nbsp; Application.Title := 'destroy me'; <br>&nbsp; &nbsp; //改变程序标题,以使FindWindow找到的是前一个实例窗口 <br>&nbsp; &nbsp; PreviousInstanceWindow := FindWindow(nil,pchar(AppName)); <br>&nbsp; //寻找前一个实例窗口句柄 <br>&nbsp; &nbsp; if PreviousInstanceWindow &lt;&gt; 0 then <br>&nbsp; &nbsp; //已经找到 <br>&nbsp; &nbsp; &nbsp; if IsIconic(PreviousInstanceWindow) then <br>&nbsp; &nbsp; &nbsp; //如该窗口最小化则恢复 <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ShowWindow(PreviousInstanceWindow,SW_RESTORE) <br>&nbsp; &nbsp; else <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SetForegroundWindow(PreviousInstanceWindow); <br>&nbsp; &nbsp; &nbsp; &nbsp;//否则如程序在后台则将其放到前台 &nbsp; <br>&nbsp; &nbsp; Application.Terminate; <br>&nbsp; &nbsp;//中止本实例 <br>&nbsp; end; <br><br>finalization &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<br>&nbsp;if mHandle &lt;&gt; 0 then <br>&nbsp;//该互斥区对象仍存在则关闭对象 <br>&nbsp; &nbsp; CloseHandle(mHandle); <br>end. <br>将上面的程序改成你的文件,试试看
 
自己写一个函数吧<br><br>function IsFileOpened(const FileName: String): Boolean;<br>var<br>&nbsp; F: File;<br>begin<br>&nbsp; Result := False;<br>&nbsp; if FileExists(FileName) then<br>&nbsp; begin<br>&nbsp; &nbsp; AssignFile(F, FileName);<br>&nbsp; &nbsp; try<br>&nbsp; &nbsp; &nbsp; Reset(F);<br>&nbsp; &nbsp; &nbsp; CloseFile(F);<br>&nbsp; &nbsp; except<br>&nbsp; &nbsp; &nbsp; Result := True;<br>&nbsp; &nbsp; end;<br>&nbsp; end;<br>end;<br>
 
后退
顶部