System.Collections.ListDictionaryInternal Error
本文关键字:Error ListDictionaryInternal Collections System | 更新日期: 2023-09-27 18:16:16
我试图创建一个程序,每次我创建一个文本文件,它会压缩文件并记录它。它适用于第一个文本文件,但当我创建第二个文本文件,我得到这个异常:System.Collections.ListDictionaryInternal
Error:The process cannot access the file 'D:'TemeC#'FilesHomework'FilesHomework' obj'Debug'New Text Document.txt' because it is being used by another process.
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.IO.Compression;
using System.Security.Permissions;
namespace FilesHomework
{
class Program
{
static void Main(string[] args)
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "D:";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.txt";
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press ''q'' to quit the sample.");
while (Console.Read() != 'q') ;
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
try {
FileInfo FileIn = new FileInfo(e.Name);
Compress(FileIn);
// FileStream LogFile = File.Open("LogFile.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite);
// File.SetAttributes("LogFile.txt", FileAttributes.Normal);
// StreamWriter sw = new StreamWriter(LogFile);
string str;
str = ("The file " + e.Name + " has been deleted at " + DateTime.Now);
// byte[] b1 = System.Text.Encoding.UTF8.GetBytes(str);
// sw.WriteLine(str);
Console.WriteLine(str);
File.Delete(e.Name);
// LogFile.Close();
// sw.Close();
}
catch(Exception er)
{
Console.WriteLine("Error:" + er.Data);
}
}
public static void Compress(FileInfo fileSelected)
{
using (FileStream originalFileStream = fileSelected.OpenRead())
{
if ((File.GetAttributes(fileSelected.FullName) &
FileAttributes.Hidden) != FileAttributes.Hidden & fileSelected.Extension != ".gz")
{
using (FileStream compressedFileStream = File.Create(fileSelected.Name+ ".gz"))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream,
CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
}
}
}
}
}
}
}
你们觉得我该怎么做?
啊,我想我看到问题了。
在您关闭编辑器中的文件之前,看起来您的代码正在尝试拾取新文件。
你需要在你的Compress方法中引入一种机制来检查文件是否可以首先打开。
查看这个答案来检查文件是否可以访问,在代码中:
是否有一种方法来检查文件是否正在使用?
编辑:我还会尝试将FileSystemWatcher事件更改为. changed,该事件在文件属性更改后触发。
我仍然会检查你是否可以通过上面的链接打开阅读