C# 判断文件存在

it2023-04-29  97

正则判断路径为网络路径还是本地路径

/// <summary> /// 识别urlStr是否是网络路径 /// </summary> /// <param name="urlStr"></param> /// <returns></returns> public bool UrlDiscern(string urlStr) { if (Regex.IsMatch(urlStr, @"((http|ftp|https)://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?")) { return true; } else { return false; } }

 判断网络路径和本地路径是否存在

/// <summary> /// 判断远程文件是否存在 /// </summary> /// <param name="fileUrl"></param> /// <returns></returns> public bool RemoteFileExists(string fileUrl) { HttpWebRequest re = null; HttpWebResponse res = null; try { re = (HttpWebRequest)WebRequest.Create(fileUrl); res = (HttpWebResponse)re.GetResponse(); if (res.ContentLength >= 0 && res.StatusCode == HttpStatusCode.OK) { //MessageBox.Show("文件存在"); return true; } } catch (Exception) { //MessageBox.Show("无此文件"); return false; } finally { if (re != null) { re.Abort();//销毁关闭连接 } if (res != null) { res.Close();//销毁关闭响应 } } return false; } /// <summary> /// 判断本地文件是否存在 /// </summary> /// <param name="path"></param> /// <returns></returns> public bool LocalFileExists(string filePath) { if (File.Exists(filePath)) { return true; } else { return false; } }

 

最新回复(0)