C# 读写文件时提示文件占用的解决方法

1.注意使用using和FileShare文件共享选项

public static class FileHelper
{
    public static void WriteAllTextWithShare(string path, string content)
    {
        using (var sw = new StreamWriter(
            new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)))
        {
            sw.Write(content);
        }
    }
    
    public static string ReadAllTextWithShare(string path)
    {
        using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (var sr = new StreamReader(fs))
        {
            return sr.ReadToEnd();
        }
    }
}

// 使用方式
FileHelper.WriteAllTextWithShare(filePath, content);
var text = FileHelper.ReadAllTextWithShare(filePath);

2.原子文件替换

public static void AtomicReplaceFile(string filePath, string newContent)
{
    string tempFile = Path.Combine(Path.GetDirectoryName(filePath), Path.GetRandomFileName());
    
    try
    {
        // 1. 将新内容写入临时文件
        File.WriteAllText(tempFile, newContent, Encoding.UTF8);

        // 2. 备份原始文件(可选)
        string backupFile = filePath + ".bak";
        if (File.Exists(filePath))
        {
            File.Replace(tempFile, filePath, backupFile, ignoreMetadataErrors: true);
        }
        else
        {
            File.Move(tempFile, filePath);
        }
    }
    catch (Exception ex)
    {
        // 3. 发生错误时清理临时文件
        if (File.Exists(tempFile))
        {
            try { File.Delete(tempFile); } catch { /* 忽略清理错误 */ }
        }
        throw new IOException($"原子替换文件失败: {ex.Message}", ex);
    }
}

3.确保文件在所有读写处均被正确释放

  本文遇到的问题是在一处不显眼的地方进行了File.Create,导致以上所有方法都失效。。。

posted @ 2025-04-10 22:18  尼古拉-卡什  阅读(268)  评论(0)    收藏  举报