gpt4 book ai didi

c# - 使用 C# 检查文件是否正在使用

转载 作者:行者123 更新时间:2023-12-05 01:41:39 25 4
gpt4 key购买 nike

我看到了这两个问题:

Check if file is in use

Is there a way to check if a file is in use?

而且他们都没有提供我需要的所有信息,我需要对一些答案进行更多澄清,但这些问题已经有好几年了,所以我不确定是否应该尝试从在这一点上。

所以我发布了一个新问题。有点像

public string myFile;
myFile = @"C:\somepath\somefile.pdf";

if (myFile isinuseorwhatever)
{
MessageBox.Show("File is in use!! Close it and try again");
return;
}
else
{
MessageBox.Show("That worked. Good job!")
//Do Stuff and lots of lines of stuff.
}

我可以使用异常处理来做到这一点,但问题是我需要在运行多行代码之前进行检查。

我觉得我需要创建一个类来检查它,然后运行该类。老实说,我对编码还很陌生,所以我不是 100% 清楚类的工作原理。

我知道如何使用 trycatch,但这在这里不起作用,因为异常发生在 try 的最后几行代码中 block ,所以所有这些东西都会在它遇到异常之前发生。就像,这个程序复制一个文件,重命名它,将它移动到一个不同的目录,然后删除原来的,这是它做的最后一件事。如果用户打开了文件,它将执行所有操作,但在尝试删除时抛出异常。我需要它在复制、重命名、移动等之前抛出异常。

最佳答案

您可以使用 FileStreamFileShare.None 锁定文件以进行独占访问。因此,如果我们想要实现提到的第一个请求,即

  1. 检查文件是否正在使用,如果是,通知用户
  2. 如果不锁,就没人打开了
  3. 复制文件
  4. 重命名文件

可以实现如下代码:

try
{

using (Stream stream = new FileStream("1.docx", FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
// Here you can copy your file
// then rename the copied file
}
}
catch (Exception ex)
{
MessageBox.Show("File is in use!! Close it and try again");
return;
}

我想你知道如何复制和重命名文件(如果没有评论它,我会在这里添加代码)。你问题的第二部分有点棘手。因为您不能使用 Filestream 来删除文件。一旦您将 filestream 设置为调用 File.Delete("YourFile.doc") ,某些人可能会在那一刻访问它。我建议您在锁定文件时将其截断,以便其他用户无法使用它。您还可以让您的流程处于循环状态,直到文件被释放。代码看起来像这样:

try
{
using (Stream stream = new FileStream("1.docx", FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
// Here you can copy your file
// then rename the copied file
using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
{
writer.Write(""); // truncate the file, making it unusable to others
}
}
while (true)
{
try
{
File.Delete("1.docx");
}
catch
{
}
}
}
catch (Exception ex)
{
MessageBox.Show("File is in use!! Close it and try again");
return;
}

关于c# - 使用 C# 检查文件是否正在使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54151880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com