C# WinForm 检测文件是否被占用

#region 检测文件状态及操作方式选择
[DllImport("kernel32.dll")]
private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
private const int OF_READWRITE = 2;
private const int OF_SHARE_DENY_NONE = 0x40;
private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
/// <summary>
/// 检测文件是否只读或被使用
/// </summary>
/// <param name="FileNames">要检测的文件</param>
/// <returns>true可用,false在用或只读</returns>
public static bool CheckFilesState(string fileName)
{
    if (!File.Exists(fileName))
        return true;//文件不存在
    if ((File.GetAttributes(fileName) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
        return false;       //文件只读
    IntPtr vHandle = _lopen(fileName, OF_READWRITE | OF_SHARE_DENY_NONE);
    if (vHandle == HFILE_ERROR)
        return false;       //文件被占用
    CloseHandle(vHandle);   //文件没被占用
    return true;
}
/// <summary>
/// 检测文件是否只读或被使用,并由用户选择是否继续操作
/// </summary>
/// <param name="fileFullName">要检测的文件</param>
/// <returns>true已在用,false未用</returns>
public static bool FileHasOpened(string fileFullName)
{
    bool lOpened = false;
    bool lRetry = true;
    do
    {
        if (!CheckFilesState(fileFullName))
        {
            if (DialogResult.Cancel == MessageBox.Show("文件只读或已经被打开,请处理后再操作!", "系统错误!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning))
            {
                lRetry = false;
                lOpened = true;
            }
        }
        else
            lRetry = false;
    } while (lRetry);
    return lOpened;
}
#endregion

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是C# WinForm上传文件的示例代码: ```csharp private void btnUpload_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; string url = "http://localhost/UploadFileWeb/WebForm1.aspx"; string paramName = "file"; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); request.ContentType = "multipart/form-data; boundary=" + boundary; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n"; string header = string.Format(headerTemplate, paramName, Path.GetFileName(filePath)); byte[] headerBytes = Encoding.UTF8.GetBytes(header); requestStream.Write(headerBytes, 0, headerBytes.Length); using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } } byte[] trailerBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); requestStream.Write(trailerBytes, 0, trailerBytes.Length); } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string responseText = reader.ReadToEnd(); MessageBox.Show(responseText); } } } } ``` 该示例代码使用HttpWebRequest类向指定的URL上传文件。在上传文件之前,需要设置请求的Method为POST,ContentType为multipart/form-data,并设置请求头部的边界(boundary)。然后,将文件内容写入请求流中,最后发送请求并获取响应。在获取响应后,可以从响应流中读取服务器返回的内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值