public int DeleteFile(string remotePath) { string url = "https://api.weipan.cn/2/fileops/delete"; //url += "?root=sandbox&path=" + HttpUtility.UrlEncode(remotePath) + "&access_token=" + _accessToken; IDictionary <string, string> postParameters = new Dictionary <string, string>(); postParameters.Add("access_token", _accessToken); postParameters.Add("root", "sandbox"); postParameters.Add("path", remotePath); CloudFileInfoModel m = new CloudFileInfoModel(); try { var request = new WebRequestHelper(url); var result = request.Post(url, postParameters); var entity = JsonHelper.DeserializeObject <SinaResponseFileInfoJsonEntity>(result); m.Bytes = 0; m.Path = entity.path; m.RootPath = entity.root; m.LastModifiedDate = Convert.ToDateTime(entity.modified); } catch (Exception ex) { throw ex; } return(1); }
public Model.CloudDisk.CloudFileInfoModel CreateDirectory(string dir) { CloudFileInfoModel m = new CloudFileInfoModel(); m.Path = dir; return(m); }
/// <summary> /// 同步远端更改到本地 /// </summary> public static void SysCloudToLocal() { while (true) { try { if (!MemoryFileManager.GetInstance().IsNeedSync()) { CloudFiles = new List <string>(); var fileInfo = new CloudFileInfoModel { Path = "/", IsDir = true }; SyncCloudFileToLocal(fileInfo); SyncCloudRemoveFileToLocal(); } Thread.Sleep(15 * 1000); } catch { } } }
public Model.CloudDisk.CloudFileInfoModel CreateDirectory(string dir) { string url = "https://api.weipan.cn/2/fileops/create_folder"; //url += "?access_token=" + _accessToken + "&root=sandbox&path=" + UrlEncoder.UrlEncode(dir); IDictionary <string, string> postParameters = new Dictionary <string, string>(); postParameters.Add("access_token", _accessToken); postParameters.Add("root", "sandbox"); postParameters.Add("path", dir); CloudFileInfoModel m = new CloudFileInfoModel(); try { var request = new WebRequestHelper(url); var result = request.Post(url, postParameters); var entity = JsonHelper.DeserializeObject <SinaResponseFileInfoJsonEntity>(result); m.Bytes = 0; m.Path = UrlEncoder.UrlDecode(entity.path); m.RootPath = entity.root; m.LastModifiedDate = Convert.ToDateTime(entity.modified); } catch (Exception ex) { throw ex; } return(m); }
public Model.CloudDisk.CloudFileInfoModel GetCloudFileInfo(string remotePath) { try { string url = "https://api.weipan.cn/2/metadata/sandbox"; WebRequestHelper helper = new WebRequestHelper(url); var result = helper.Get(url + remotePath + "?access_token=" + _accessToken); CloudFileInfoModel m = new CloudFileInfoModel(); var fileInfo = JsonHelper.DeserializeObject <SinaResponseFileInfoJsonEntity>(result); m.Bytes = Convert.ToDouble(fileInfo.bytes); m.DiskType = CloudDiskType.SINA; m.Path = fileInfo.path; m.IsDir = Convert.ToBoolean(fileInfo.is_dir); m.LastModifiedDate = Convert.ToDateTime(fileInfo.modified); m.MD5 = fileInfo.md5; m.SHA1 = fileInfo.sha1; if (fileInfo.contents != null) { m.Contents = new List <CloudFileInfoModel>(); foreach (var oneDir in fileInfo.contents) { CloudFileInfoModel subDir = new CloudFileInfoModel(); subDir.Bytes = Convert.ToDouble(oneDir.bytes); subDir.Path = oneDir.path; subDir.IsDir = Convert.ToBoolean(oneDir.is_dir); subDir.LastModifiedDate = Convert.ToDateTime(oneDir.modified); subDir.MD5 = oneDir.md5; subDir.SHA1 = oneDir.sha1; m.Contents.Add(subDir); } } return(m); } catch (System.Net.WebException webEx) { HttpWebResponse errorResponse = webEx.Response as HttpWebResponse; if (errorResponse.StatusCode == HttpStatusCode.NotFound) { // return(null); } //webEx.Status == System.Net.WebExceptionStatus.CacheEntryNotFound //throw webEx; } catch (Exception ex) { throw ex; } return(null); }
public Model.CloudDisk.CloudFileInfoModel GetCloudFileInfo(string remotePath) { string url = "http://bcs.duapp.com/" + _bucketName; //if (remotePath == "/" || string.IsNullOrEmpty(remotePath)) //{ //} //else //{ // url += remotePath; //} string flag = "MBO"; string para = "?sign=" + flag + ":" + _appKey + ":"; string content = flag + "\n" + "Method=GET" + "\n" + "Bucket=" + _bucketName + "\n" + "Object=/" + "\n"; //+ "Object=" + remotePath + "\n"; string sign = BaiduSignatureHelper.GetSignature(content, _appSecret); para = para + sign; WebRequestHelper helper = new WebRequestHelper(url); url = url + para; var result = helper.Get(url); BaiduFileInfo info = JsonHelper.DeserializeObject <BaiduFileInfo>(result); CloudFileInfoModel m = null; if (info != null) { foreach (BaiduObjectList obj in info.object_list) { if (obj.Object == remotePath) { m = new CloudFileInfoModel(); m.Bytes = Convert.ToDouble(obj.size); m.IsDir = obj.is_dir == "1"; m.Path = obj.Object; m.MD5 = obj.content_md5; break; } } } return(m); }
public CloudFileInfoModel CreateDirectory(string dir) { SortedDictionary <string, string> ParamList = getParamList(); ParamList.Add("root", "app_folder"); ParamList.Add("path", dir); string SourceString = GetApiSourceString(this.createFolderUrl, ParamList); string SecretKey = GetSecretKey(); string Sign = GetSignature(SourceString, SecretKey); ParamList.Add("oauth_signature", Sign); string url = this.createFolderUrl + "?" + ParamToUrl(ParamList, false); object jsonAccess = GetGeneralContent(url); XmlNode node = JsonHelper.DeserializeToXmlNode(jsonAccess.ToString()); CloudFileInfoModel fileInfo = new CloudFileInfoModel(); fileInfo.Path = PathConverter.RemotePathToLocalPath(Convert.ToString(node.ChildNodes[0].SelectSingleNode("path").InnerText)); return(fileInfo); }
/// <summary> /// 上传一个文件,具体上传至哪个网盘由内部决定,有可能会抛出异常,异常在外面处理 /// </summary> /// <param name="type">上传类型,新增或者更新</param> /// <param name="filePath">文件相对路径,含文件名</param> /// <param name="fileContent">文件内容</param> /// <returns></returns> public CloudFileInfoModel UploadFile(CloudFileUploadType type, string filePath, byte[] fileContent) { CloudFileInfoModel uploaded = new CloudFileInfoModel(); //所有传入的路径都进行一次转换 filePath = PathConverter.LocalPathToRemotePath(filePath); if (type == CloudFileUploadType.Create) { List <ICloudDiskAPI> apis = GetOptimizedDisk(); if (apis != null) { foreach (ICloudDiskAPI oneApi in apis) { uploaded = oneApi.UploadFile(fileContent, filePath); } } else { //throw new Exception("没有可用的网盘可供上传!"); return(null); } } //修改 if (type == CloudFileUploadType.Update) { //遍历所有网盘 foreach (ICloudDiskAPI api in _loadedCloudDiskApi) { if (api.GetCloudFileInfo(filePath) != null) { uploaded = api.UploadFile(fileContent, filePath); } } } //在传出返回值之前将远程路径的形式替换成本地路径 if (uploaded != null) { uploaded.LocalPath = PathConverter.RemotePathToLocalPath(uploaded.Path); } return(uploaded); }
public Model.CloudDisk.CloudFileInfoModel UploadFile(byte[] fileContent, string filePath) { string url = "http://bcs.duapp.com/" + _bucketName + filePath; string flag = "MBO"; string para = "?sign=" + flag + ":" + _appKey + ":"; string content = flag + "\n" + "Method=PUT" + "\n" + "Bucket=" + _bucketName + "\n" + "Object=" + filePath + "\n"; //+ "Object=" + remotePath + "\n"; string sign = BaiduSignatureHelper.GetSignature(content, _appSecret); para = para + sign; url = url + para; CloudFileInfoModel result = new CloudFileInfoModel(); try { WebRequest request = WebRequest.Create(url); request.Method = "PUT"; request.ContentLength = fileContent.Length; //request.GetRequestStream Stream newStream = request.GetRequestStream(); newStream.Write(fileContent, 0, fileContent.Length); // Close the Stream object. newStream.Close(); Stream stream = request.GetResponse().GetResponseStream(); StreamReader reader = new StreamReader(stream, Encoding.UTF8); string responseString = reader.ReadToEnd(); result.Path = filePath; } catch (Exception ex) { //throw ex; result = null; } return(result); }
/// <summary> /// 移动远程文件 /// </summary> /// <param name="originPath">原始路径</param> /// <param name="newPath">新路径</param> /// <param name="isCopy">是否需要复制</param> /// <returns>新文件的信息</returns> public CloudFileInfoModel MoveFile(CloudDiskType type, string originPath, string newPath, bool isCopy) { CloudFileInfoModel m = new CloudFileInfoModel(); try { //CloudDiskType type = GetDiskTypeByURL(originPath); ICloudDiskAPI oneApi; if (IsDiskTypeLoaded(type, out oneApi)) { oneApi.MoveFile(originPath, newPath, isCopy); } else { throw new Exception("文件地址不正确或者网盘接口模块没有被正确加载!"); } } catch (Exception ex) { throw new Exception("移动远程文件信息出错!" + ex.Message); } return(m); }
/// <summary> /// 同步云端的文件到本地。 /// </summary> public static void SyncCloudFileToLocal(CloudFileInfoModel fileInfo) { try { var root = LocalDiskPathHelper.GetPath(); var cloudManager = new CloudDiskManager(); var cloudFile = cloudManager.GetCloudFileInfo( CloudDiskType.NOT_SPECIFIED, fileInfo.IsDir, fileInfo.Path); if (cloudFile != null) { CloudFiles.Add(cloudFile.LocalPath); var path = root + cloudFile.LocalPath; if (fileInfo.Path != "/") { if (cloudFile.IsDir) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } else { var needCreat = false; if (!File.Exists(path)) { needCreat = true; } else { var file = new FileInfo(path); if (cloudFile.LastModifiedDate.HasValue) { if (file.LastWriteTime < cloudFile.LastModifiedDate) { File.Delete(path); needCreat = true; } } } if (needCreat) { var fileContent = cloudManager.DownloadFile(CloudDiskType.NOT_SPECIFIED, cloudFile.Path); File.WriteAllBytes(path, fileContent); } } } if (cloudFile != null && cloudFile.Contents != null && cloudFile.Contents.Count > 0) { foreach (var subFile in cloudFile.Contents) { if (!cloudFile.Path.EndsWith("/")) { cloudFile.Path = cloudFile.Path + "/"; } subFile.Path = cloudFile.Path + subFile.name; SyncCloudFileToLocal(subFile); } } } }catch (Exception ex) { } }
/// <summary> /// 获取一个远程文件的信息 /// </summary> /// <param name="type">网盘类型</param> /// <param name="isGetDirectory">是否是获取文件夹,否的话表示获取文件</param> /// <param name="remotePath">远程文件的相对路径</param> /// <returns></returns> public CloudFileInfoModel GetCloudFileInfo(CloudDiskType type, bool isGetDirectory, string remotePath) { CloudFileInfoModel m = null; try { //CloudDiskType type = GetDiskTypeByURL(remotePath); //所有传入的文件都进行一次转换 remotePath = PathConverter.LocalPathToRemotePath(remotePath); if (isGetDirectory) { //是文件夹,需要遍历所有可用网盘,将所有子文件和子文件夹信息加总一起反馈 foreach (ICloudDiskAPI api in _loadedCloudDiskApi) { var tmp_dir = api.GetCloudFileInfo(remotePath); if (tmp_dir != null) { if (m == null) { m = new CloudFileInfoModel(); m.Path = tmp_dir.Path; m.name = tmp_dir.name; m.IsDir = tmp_dir.IsDir; m.LastModifiedDate = tmp_dir.LastModifiedDate; m.Contents = new List <CloudFileInfoModel>(); } //将每个找到网盘的子目录和子文件都加入到返回值m里去. if (tmp_dir.Contents != null) { foreach (CloudFileInfoModel subDir in tmp_dir.Contents) { m.Contents.Add(subDir); } } } } } else { //是文件需要找到是哪个网盘 if (type == CloudDiskType.NOT_SPECIFIED) { //未指定类型,必须便利查找属于哪个网盘 foreach (ICloudDiskAPI api in _loadedCloudDiskApi) { m = api.GetCloudFileInfo(remotePath); if (m != null) { //第一个找到就返回 break; } } if (m == null) { //全部遍历了依然没有找到 throw new Exception("文件地址不正确或者网盘接口模块没有被正确加载!"); } } else { //指定类型的 ICloudDiskAPI oneApi; if (IsDiskTypeLoaded(type, out oneApi)) { m = oneApi.GetCloudFileInfo(remotePath); } else { throw new Exception("文件地址不正确或者网盘接口模块没有被正确加载!"); } } } } catch (Exception ex) { throw new Exception("获取远程文件信息出错!" + ex.Message); } //在传出返回值之前将远程路径的形式替换成本地路径 if (m != null) { if (m.Path != null) { m.LocalPath = PathConverter.RemotePathToLocalPath(m.Path); } } return(m); }
public CloudFileInfoModel UploadFile(byte[] fileContent, string filePath) { NameValueCollection stringDict = new NameValueCollection(); stringDict.Add("file", "fileKeyValue"); object jsonAccess = GetGeneralContent(this.fileUploadLocationUrl); XmlNode node = JsonHelper.DeserializeToXmlNode(jsonAccess.ToString()); String updateUrl = Convert.ToString(node.ChildNodes[0].SelectSingleNode("url").InnerText); String status = Convert.ToString(node.ChildNodes[0].SelectSingleNode("stat").InnerText); if (status.Equals("OK")) { String Url = string.Format(this.fileUploadUrl, updateUrl); SortedDictionary <string, string> ParamList = getParamList(); ParamList.Add("root", "app_folder"); ParamList.Add("path", filePath); ParamList.Add("overwrite", "true"); StringBuilder sb = new StringBuilder(); sb.Append("POST&"); sb.Append(UrlEncode(Url) + "&"); string InnerParam = ParamToUrl(ParamList, true); sb.Append(UrlEncode(InnerParam)); string SourceString = sb.ToString(); string SecretKey = GetSecretKey(); string Sign = GetSignature(SourceString, SecretKey); ParamList.Add("oauth_signature", Sign); String finalUrl = Url + "?" + ParamToUrl(ParamList, false); string responseContent; var memStream = new MemoryStream(); var webRequest = (HttpWebRequest)WebRequest.Create(finalUrl); // 边界符 var boundary = "---------------" + DateTime.Now.Ticks.ToString("x"); // 边界符 var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); // 最后的结束符 var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); // 设置属性 webRequest.Method = "POST"; webRequest.Timeout = 10000; webRequest.ContentType = "multipart/form-data; boundary=" + boundary; // 写入文件 const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n"; var header = string.Format(filePartHeader, "file", filePath); var headerbytes = Encoding.UTF8.GetBytes(header); memStream.Write(beginBoundary, 0, beginBoundary.Length); memStream.Write(headerbytes, 0, headerbytes.Length); memStream.Write(fileContent, 0, fileContent.Length); // 写入字符串的Key var stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}\r\n"; foreach (byte[] formitembytes in from string key in stringDict.Keys select string.Format(stringKeyHeader, key, stringDict[key]) into formitem select Encoding.UTF8.GetBytes(formitem)) { memStream.Write(formitembytes, 0, formitembytes.Length); } // 写入最后的结束边界符 memStream.Write(endBoundary, 0, endBoundary.Length); webRequest.ContentLength = memStream.Length; var requestStream = webRequest.GetRequestStream(); memStream.Position = 0; var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); var httpWebResponse = (HttpWebResponse)webRequest.GetResponse(); using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { responseContent = httpStreamReader.ReadToEnd(); } httpWebResponse.Close(); webRequest.Abort(); node = JsonHelper.DeserializeToXmlNode(responseContent.ToString()); CloudFileInfoModel fileInfo = new CloudFileInfoModel(); fileInfo.Size = Convert.ToString(node.ChildNodes[0].SelectSingleNode("size").InnerText); fileInfo.Path = PathConverter.RemotePathToLocalPath(filePath); return(fileInfo); } return(null); }
public CloudFileInfoModel GetCloudFileInfo(string remotePath) { String metaUrl = String.Format(this.metadataUrl, remotePath); SortedDictionary <string, string> ParamList = getParamList(); ParamList.Add("list", "true"); string SourceString = GetApiSourceString(metaUrl, ParamList); string SecretKey = GetSecretKey(); string Sign = GetSignature(SourceString, SecretKey); ParamList.Add("oauth_signature", Sign); string URL = metaUrl + "?" + ParamToUrl(ParamList, false); var jsonAccess = GetGeneralContent(URL); var entity = JsonHelper.DeserializeObject <KingsoftResponseFileInfoJsonEntity>(jsonAccess); if (jsonAccess != "") { CloudFileInfoModel fileInfo = new CloudFileInfoModel(); fileInfo.Hash = entity.hash; fileInfo.name = entity.name; fileInfo.LastModifiedDate = Convert.ToDateTime(entity.modify_time); fileInfo.Size = entity.size; fileInfo.Path = entity.path; if (entity.type == "folder") { fileInfo.IsDir = true; } else { fileInfo.IsDir = false; } if (entity.files != null) { fileInfo.Contents = new List <CloudFileInfoModel>(); foreach (var oneDir in entity.files) { CloudFileInfoModel subDir = new CloudFileInfoModel(); subDir.LastModifiedDate = Convert.ToDateTime(oneDir.modify_time); subDir.name = oneDir.name; subDir.Size = oneDir.size; if (oneDir.type == "folder") { subDir.IsDir = true; } else { subDir.IsDir = false; } fileInfo.Contents.Add(subDir); } } return(fileInfo); } else { return(null); } }
public Model.CloudDisk.CloudFileInfoModel UploadFile(byte[] fileContent, string filePath) { string url = "https://upload-vdisk.sina.com.cn/2/files/sandbox"; var contentEncoding = "UTF-8";//"iso-8859-1"; var request = new WebRequestHelper(url); string fileName = filePath.Substring(filePath.LastIndexOf("/") + 1); url = url + filePath + "?access_token=" + _accessToken; var boundary = Guid.NewGuid().ToString(); var header = string.Format("--{0}", boundary); var footer = string.Format("--{0}--", boundary); var contents = new StringBuilder(); //contents.AppendLine(header); //contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "status")); //contents.AppendLine("Content-Type: text/plain; charset=US-ASCII"); //contents.AppendLine("Content-Transfer-Encoding: 8bit"); //contents.AppendLine(); //contents.AppendLine(HttpUtility.UrlEncode(status)); //contents.AppendLine(header); //contents.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", "source")); //contents.AppendLine("Content-Type: text/plain; charset=US-ASCII"); //contents.AppendLine("Content-Transfer-Encoding: 8bit"); //contents.AppendLine(); //contents.AppendLine(this.appKey); string fileHeader = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", "file", fileName); string fileData = System.Text.Encoding.GetEncoding(contentEncoding).GetString(fileContent); request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary); contents.AppendLine(header); contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "FileName")); contents.AppendLine(); contents.AppendLine(fileName); contents.AppendLine(header); contents.AppendLine(fileHeader); contents.AppendLine("Content-Type: application/octet-stream;"); //contents.AppendLine("Content-Length:" + fileContent.LongLength.ToString()); //contents.AppendLine("Content-Transfer-Encoding: binary"); contents.AppendLine(); contents.AppendLine(fileData); contents.AppendLine(footer); //contents.AppendLine(); try { var result = request.Post(url, null, null, null, contents.ToString()); var entity = JsonHelper.DeserializeObject <SinaResponseFileInfoJsonEntity>(result); CloudFileInfoModel fileInfo = new CloudFileInfoModel(); fileInfo.Bytes = Convert.ToDouble(entity.bytes); fileInfo.Path = entity.path; fileInfo.LastModifiedDate = Convert.ToDateTime(entity.modified); fileInfo.MD5 = entity.md5; fileInfo.SHA1 = entity.sha1; fileInfo.RootPath = entity.root; fileInfo.DiskType = CloudDiskType.SINA; return(fileInfo); } catch (WebException webEx) { HttpWebResponse errorResponse = webEx.Response as HttpWebResponse; string ex_txt = ""; string strContentEncoding = "utf-8"; System.IO.StreamReader sr = new StreamReader(webEx.Response.GetResponseStream(), System.Text.Encoding.GetEncoding(strContentEncoding)); ex_txt = sr.ReadToEnd(); if (errorResponse.StatusCode == HttpStatusCode.Forbidden) { // //throw new Exception("上传文件时出错!可能是权限不足!" + ex_txt); return(null); } } catch (Exception ex) { //throw ex; return(null); } return(null); }