我怀疑是否有任何方法可以自动了解其他程序是否未使用特定文件。让我更好地解释这个想法。
我有一个由其他软件打开和使用的文件,我想知道MATLAB是否该文件已被软件使用,然后随心所欲。到目前为止,我有一个临时解决方案,如果文件没有改变权重,则会检查每个句点,但此解决方案会进行不必要的搜索。
顺便感谢!
答案 0 :(得分:0)
如果您使用的是Windows,并且您正在运行最近发布的支持.NET 的matlab(更新近r2009a,据我所知),这里有一个快速解决方案让一些{ {3}}对象监视器为您更改并在需要时发送适当的通知:
%% --- Watch for file events in some directory
function [watchers] = WatchFolder(name)
%[
% Get folder's name
if (exist(name, 'dir'))
folder = name;
elseif (exist(name, 'file'))
fullFilename = which(name);
[folder, ~, ~] = fileparts(fullFilename);
else
error('Argument must be a file or folder');
end
% Create file system watcher object
fileObj = System.IO.FileSystemWatcher(folder);
fileObj.EnableRaisingEvents = true;
% Select events to monitor for
filter = bitor(System.IO.NotifyFilters.FileName, System.IO.NotifyFilters.DirectoryName);
filter = bitor(filter, System.IO.NotifyFilters.Attributes);
filter = bitor(filter, System.IO.NotifyFilters.Size);
filter = bitor(filter, System.IO.NotifyFilters.LastWrite);
filter = bitor(filter, System.IO.NotifyFilters.LastAccess);
filter = bitor(filter, System.IO.NotifyFilters.CreationTime);
filter = bitor(filter, System.IO.NotifyFilters.Security);
fileObj.NotifyFilter = filter;
% Add listeners (Need to be kept alive in scope)
watchers.Changed = addlistener(fileObj, 'Changed', @onFolderModification);
watchers.Created = addlistener(fileObj, 'Created', @onFolderModification);
watchers.Deleted = addlistener(fileObj, 'Deleted', @onFolderModification);
watchers.Renamed = addlistener(fileObj, 'Renamed', @onFolderModification);
%]
%% --- This event is raise on any folder modification and as long as listeners are alive
function [] = onFolderModification(source, args) %#ok<INUSL>
%[
fprintf('%s: %s\n', char(args.ChangeType.ToString()), char(args.Name));
%]
小心,这只是测试代码,你需要让监听器保持活着继续接收事件......由你来适应你的情况(插入gui,只看一些特定的文件,检查文件是否(s)是否正在使用或未收到通知等...)。
以下是我的命令窗口中使用当前测试代码的一些日志:
>> wf= WatchFolder('C:\Users\CitizenInsane\Desktop');
Created: Nouveau Microsoft Word Document.docx
Renamed: MyDocument.docx
Changed: MyDocument.docx
Created: ~$Document.docx
Changed: ~$Document.docx
Created: ~WRD0000.tmp
Changed: ~WRD0000.tmp
Changed: ~WRD0000.tmp
Changed: ~WRD0000.tmp
Changed: ~WRD0000.tmp
Changed: ~WRD0000.tmp
Changed: ~WRD0000.tmp
Renamed: ~WRL0001.tmp
Renamed: MyDocument.docx
Changed: ~WRL0001.tmp
Changed: MyDocument.docx
Changed: MyDocument.docx
>> clear wf; % Stops receiving events (i.e. listeners no longer referenced)