[英]C# file copy error file is being used by another program
我有一个目录,我在其中制作/放置一些文件。 当filesystemwatcher看到一个新文件时,它会将该文件复制到第二个目录中。 但是当我直接在dir1中创建一个文件时,它会关闭,说它被另一个程序使用。
我该如何摆脱这个问题?
这是我的代码:
using System;
using System.IO;
using System.Configuration;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ChaloSync
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool pause = false;
String source = ConfigurationManager.AppSettings[@"Directory1"];
String target = ConfigurationManager.AppSettings[@"Directory2"];
private void start()
{
pause = true;
Start.Text = "Pause";
fileSystemWatcher1.EnableRaisingEvents = true;
}
static void config()
{
foreach (string key in ConfigurationManager.AppSettings)
{
string value = ConfigurationManager.AppSettings[key];
MessageBox.Show(value);
}
}
private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
{
listBox1.Items.Add("File changed> " + e.FullPath + " -Date:" + DateTime.Now);
}
private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
{
listBox1.Items.Add("File created> " + e.FullPath + " -Date:" + DateTime.Now);
File.Copy(e.FullPath , Path.Combine(target,e.Name));
}
private void fileSystemWatcher1_Deleted(object sender, System.IO.FileSystemEventArgs e)
{
listBox1.Items.Add("File deleted> " + e.FullPath + " -Date:" + DateTime.Now);
}
private void fileSystemWatcher1_Renamed(object sender, System.IO.RenamedEventArgs e)
{
listBox1.Items.Add("File renamed> " + e.FullPath + " -Date:" + DateTime.Now);
}
private void Start_Click(object sender, EventArgs e)
{
fileSystemWatcher1.Path = source;
if (!pause)
{
start();
}
else
{
pause = false;
Start.Text = "Start";
fileSystemWatcher1.EnableRaisingEvents = false;
}
}
}
}
如果您在读取或写入文件时遇到锁定问题,请检查FileShare
选项。
请检查此链接 。
不一样的问题,但由同样的问题引起。 解决方案对您有好处。
此方法的典型问题是在触发事件时仍在复制文件。 显然,您将获得异常,因为文件在复制期间被锁定。 大文件特别容易出现异常。
作为一种解决方法,您可以先复制该文件,然后重命名该文件并收听重命名事件。
或者另一种选择是使用while循环检查是否可以使用写访问权打开文件。 如果可以,您将知道复制已完成。 C#代码可能如下所示(在生产系统中,您可能希望具有最大重试次数或超时而不是一会儿(true)):
(从这里复制: 当多个文件添加到目录时,文件访问错误与FileSystemWatcher )
重命名和创建正在同时进行。 所以你不能复制它,因为它已经被用来重命名它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.