public static string GetObject(string objectName) { var client = new OssClient(endpoint, accessKeyId, accessKeysecret); try { var obj = client.GetObject(bucketName, objectName); using (var requestStream = obj.Content) { var buf = new byte[maxLength]; var len = requestStream.Read(buf, 0, maxLength); var str = Encoding.ASCII.GetString(buf); return(str); } } catch { return(null); } }
public void PrivateDownloadFile(string LocalFileFullName, ProgressBar UIViewProg) { try { OssClient MyOSSClient = new OssClient(MyALiYunOSSOTSLogin.MyAccessID, MyALiYunOSSOTSLogin.MyAccessKey); OssObject MyOssObject = MyOSSClient.GetObject(MyALiYunOSSOTSLogin.MyBucketName, MyALiYunOSSOTSLogin.PrefixStr + MyALiYunOSSOTSLogin.FileKeyName); string MyFileLenghtStr = MyOssObject.Metadata.UserMetadata["FileLength"]; long MyReceiveBytesCount = long.Parse(MyFileLenghtStr);//MyOssObject.Content.Length; if (UIViewProg != null) { UIViewProg.Maximum = (int)MyReceiveBytesCount;//220 * 10000;//(int)MyReceiveBytesCount; } Stream MyResponseStream = MyOssObject.Content; Stream MySaveFileStream = new FileStream(LocalFileFullName, FileMode.Create); long MyDownloadedByteLenght = 0; byte[] MyPreBuffer = new byte[1024]; int MyReadHeadSize = MyResponseStream.Read(MyPreBuffer, 0, (int)MyPreBuffer.Length); while (MyReadHeadSize > 0) { MyDownloadedByteLenght = MyReadHeadSize + MyDownloadedByteLenght; Application.DoEvents(); MySaveFileStream.Write(MyPreBuffer, 0, MyReadHeadSize); if (UIViewProg != null) { UIViewProg.Value = (int)MyDownloadedByteLenght; } MyReadHeadSize = MyResponseStream.Read(MyPreBuffer, 0, (int)MyPreBuffer.Length); } UIViewProg.Value = UIViewProg.Maximum; MySaveFileStream.Close(); MyResponseStream.Close(); ResultMessageStr = "文件私读下载成功!"; } catch (Exception InforExcep) { ResultMessageStr = "文件私读下载错误:" + InforExcep.Message; //throw; } }
public string GetObject(string filename) { StringBuilder sb = new StringBuilder(); var result = client.GetObject(bucketName, filename); using (var requestStream = result.Content) { int length = 4 * 1024; var buf = new byte[length]; while (true) { length = requestStream.Read(buf, 0, length); if (length == 0) { break; } sb.Append(Encoding.UTF8.GetString(buf.Take(length).ToArray())); } } return(sb.ToString()); }
/// <summary> /// 获取对象 /// </summary> /// <param name="containerName"></param> /// <param name="blobName"></param> /// <returns></returns> public async Task <Stream> GetBlobStream(string containerName, string blobName) { try { return(await Task.Run(() => { var blob = _ossClient.GetObject(containerName, blobName); if (blob == null) { throw new StorageException(StorageErrorCode.FileNotFound.ToStorageError(), new Exception("没有找到该文件")); } return blob.Content; })); } catch (Exception ex) { throw new StorageException(StorageErrorCode.ErrorOpeningBlob.ToStorageError(), new Exception(ex.ToString())); } }
/// <inheritdoc/> public async Task <Stream> GetBlobStream(string containerName, string blobName) { try { return(await Task.Run(() => { var key = $"{containerName}/{blobName}"; var blob = _ossClient.GetObject(_cfg.BucketName, key).HandlerError("获取对象出错"); if (blob == null || blob.ContentLength == 0) { throw new StorageException(StorageErrorCode.FileNotFound.ToStorageError(), new Exception("没有找到该文件")); } return blob.Content; })); } catch (Exception ex) { throw new StorageException(StorageErrorCode.ErrorOpeningBlob.ToStorageError(), new Exception(ex.ToString())); } }
public static void getObjectBySignedUrl2() { const string accessKeyId = "<your access key id>"; const string accessKeySecret = "<your access key secret>"; const string endpoint = "<valid host name>"; const string bucketName = "<bucket name>"; const string key = "<object name>"; OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { var metadata = client.GetObjectMetadata(bucketName, key); var etag = metadata.ETag; var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get); // Generates url signature for accessing specified object. var uri = client.GeneratePresignedUri(req); Console.WriteLine(uri.ToString()); OssObject ossObject = client.GetObject(uri); var file = File.Open("<file to hold object content>", FileMode.OpenOrCreate); Stream stream = ossObject.Content; byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); file.Write(bytes, 0, bytes.Length); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } }
private void downloadFile(OssClient client, String bucketName, string key, string filePath) { bool b = false; FileStream fs = null; try { GetObjectRequest downloadRequest = new GetObjectRequest(bucketName, key); fs = new FileStream(filePath, FileMode.OpenOrCreate); client.GetObject(downloadRequest, fs); Process.Start(filePath); } catch (Exception ex) { b = true; MessageBox.Show(this, "文件下载失败。"); LogHelper.Error(ex.Message); } finally { if (fs != null) { fs.Flush(); fs.Close(); fs.Dispose(); } if (b) { if (File.Exists(filePath)) { File.Delete(filePath); if (!Directory.Exists(DownloadPath)) { Directory.CreateDirectory(DownloadPath); } } } } }
/// <summary> /// 下载文件 /// </summary> /// <param name="key">文件唯一标识</param> /// <returns></returns> public Stream Download(string key) { try { var obj = _ossClient.GetObject(_bucketName, key); Stream requestStream = obj.Content; MemoryStream memoryStream = new MemoryStream(); const int bufferLength = 1024; int actual; byte[] buffer = new byte[bufferLength]; while ((actual = requestStream.Read(buffer, 0, bufferLength)) > 0) { memoryStream.Write(buffer, 0, actual); } memoryStream.Position = 0; return(memoryStream); } catch (Exception e) { throw new Exception("Oss下载错误:" + e.Message); } }
public static void GetObjectBySignedUrlWithClient(string bucketName, string key) { try { var metadata = client.GetObjectMetadata(bucketName, key); var etag = metadata.ETag; var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get); // Generates url signature for accessing specified object. var uri = client.GeneratePresignedUri(req); OssObject ossObject = client.GetObject(uri); using (var file = File.Open("fileToSave", FileMode.OpenOrCreate)) { using (Stream stream = ossObject.Content) { int length = 4 * 1024; var buf = new byte[length]; do { length = stream.Read(buf, 0, length); file.Write(buf, 0, length); } while (length != 0); } } Console.WriteLine("Get object by signatrue succeeded."); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } }
public static string GetImageFromPath(string name) { string image = ""; try { var obj = client.GetObject(bucketName, name); using (var requestStream = obj.Content) { byte[] buf = new byte[10000]; var fs = File.Open(name, FileMode.OpenOrCreate); var len = 0; while ((len = requestStream.Read(buf, 0, 10000)) != 0) { fs.Write(buf, 0, len); } fs.Close(); int count = 0; for (int i = 0; i < 10000; i++) { if (buf[i] == '\0') { count = i; break; } } byte[] temBuf = new byte[count]; for (int i = 0; i < count; i++) { temBuf[i] = buf[i]; } image = Encoding.Default.GetString(temBuf); } } catch (Exception ex) { Console.WriteLine("Get object failed. {0}", ex.Message); } return(image); }
/// <summary> /// 从指定的OSS存储空间中获取指定的文件 /// </summary> /// <param name="key">要获取的文件的名称</param> /// <param name="fileToDownload">文件保存的本地路径</param> public static ServerResponse Down(string key, string fileToDownload) { try { var info = Client.GetObject(Config.BucketName, key); using (var requestStream = info.Content) { var buf = new byte[1024]; var fs = File.Open(fileToDownload, FileMode.OpenOrCreate); var len = 0; while ((len = requestStream.Read(buf, 0, 1024)) != 0) { fs.Write(buf, 0, len); } fs.Close(); } return(ResponseProvider.Success("成功")); } catch (Exception ex) { return(ResponseProvider.Success("失败:" + ex.Message)); } }
public static void GetObjectProgress(string bucketName) { const string key = "GetObjectProgress"; try { client.PutObject(bucketName, key, fileToUpload); var getObjectRequest = new GetObjectRequest(bucketName, key); getObjectRequest.StreamTransferProgress += streamProgressCallback; var ossObject = client.GetObject(getObjectRequest); using (var stream = ossObject.Content) { var buffer = new byte[1024 * 1024]; var bytesTotal = 0; var bytesRead = 0; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) { bytesTotal += bytesRead; // Process read data // TODO } } Console.WriteLine("Get object:{0} succeeded", key); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } }
public static void ResizeImage(string bucketName) { try { client.PutObject(bucketName, key, imageFile); // 图片缩放 var process = "image/resize,m_fixed,w_100,h_100"; var ossObject = client.GetObject(new GetObjectRequest(bucketName, key, process)); WriteToFile(dirToDownload + "/sample.pdf", ossObject.Content); Console.WriteLine("Get Object:{0} with process:{1} succeeded ", key, process); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } }
public Stream Get(string fileName) { return(_client.GetObject(_bucketName, fileName).Content); }
static void convertthreadwork() { while (true) { Thread.Sleep(1000); if (rarqueue.Count > 0) { rarmessage newrar = rarqueue.Dequeue(); currentwid = newrar.mid; #if OSSDOWNLOAD OssClient client = new OssClient(Config.Endpoint, Config.AccessKeyId, Config.AccessKeySecret); const string bucketName = "coresnow-circle"; try { var result = client.GetObject(bucketName, newrar.rarpath); using (var requestStream = result.Content) { string path = @"F:\uev";//\Content; path = signidpropath; Utility.SubDirectoryDelete(path + "/Content"); using (var fs = File.Open(path + "/Saved/x.rar", FileMode.Create)) { int length = 4 * 1024; var buf = new byte[length]; do { length = requestStream.Read(buf, 0, length); fs.Write(buf, 0, length); } while (length != 0); } Console.WriteLine("writefileok :" + result.ContentLength); string apppath = @"E:\Program Files\7-Zip\7zG.exe"; apppath = zip7app; string passArguments = "x F:/uev/Saved/x.rar -oF:/uev/Content"; passArguments = zip7appargument; Process z7p = Utility.CommandRun(apppath, passArguments); z7p.WaitForExit(); IPAddress ipAd = IPAddress.Parse("192.168.1.240"); ipAd = IPAddress.Parse(tcplocal); TcpListener myList = new TcpListener(ipAd, 8003); myList.Start(); string projectpath = @"F:\uev/pro422.uproject"; string Arguments = ""; projectpath = unrealprojectpath; Arguments = projectshouldlaunched; Process mpro = Utility.CommandRun(projectpath, Arguments); Socket st = myList.AcceptSocket(); TCPClient tcpClient = new TCPClient(st); tcpClient.mtcplistener = myList; tcpClient.mprocess = mpro; } } catch (Exception e) { window_file_log.Log(" mmessage.rarpath :" + e); var payload = new Dictionary <string, string> { { "result", "failure" }, { "reason", "访问的RAR文件不存在" }, { "mid", Program.currentwid }, }; string strPayload = JsonConvert.SerializeObject(payload); HttpContent httpContent = new StringContent(strPayload, Encoding.UTF8, "application/json"); int retrycounter = 0; retry: window_file_log.Log("retrycounter :" + retrycounter); window_file_log.Log(strPayload); int shouldretry = 0; HttpclientHelper.httppost(Program.remotehttpserver, httpContent, (ref string strparameter, ref byte[] bytearray) => { window_file_log.Log(strparameter); if (!String.IsNullOrEmpty(strparameter)) { if (!strparameter.Contains("\"data\":true")) { shouldretry = 1; retrycounter++; } } }); if (shouldretry == 1 && retrycounter < 10) { Thread.Sleep(1000 * 60 * 10); goto retry; } } #else //httpdownload HttpclientHelper.httpget(newrar.rarpath, (ref string str, ref byte[] bytearray) => { string path = AppDomain.CurrentDomain.BaseDirectory; path += "x.rar"; path = @"F:\uev";//\Content; Utility.SubDirectoryDelete(path + "/Content"); //Thread.Sleep(5000); File.WriteAllBytes(path + "/Saved/x.rar", bytearray); Console.WriteLine("writefileok :" + bytearray.Length); //Thread.Sleep(5000); string apppath = @"E:\Program Files\7-Zip\7zG.exe"; string passArguments = "x F:/uev/Saved/x.rar -oF:/uev/Content"; Process z7p = Utility.CommandRun(apppath, passArguments); z7p.WaitForExit(); IPAddress ipAd = IPAddress.Parse("192.168.1.240"); TcpListener myList = new TcpListener(ipAd, 8003); myList.Start(); string projectpath = @"F:\uev/pro422.uproject"; string Arguments = ""; projectpath = @"C:\Program Files\Epic Games\UE_4.22\Engine\Binaries\Win64/UE4Editor.exe"; Arguments = @"F:\uev/pro422.uproject"; Process mpro = Utility.CommandRun(projectpath, Arguments); Socket st = myList.AcceptSocket(); TCPClient tcpClient = new TCPClient(st); tcpClient.mtcplistener = myList; tcpClient.mprocess = mpro; }); #endif evtObj.WaitOne(); } } }
public Stream GetFileFromAliOss(string FileKey) { OssObject aliobj = client.GetObject(AliYunOssConfig.BucketName, FileKey); return(aliobj.Content); }
/// <summary> /// 开始下载任务执行 /// </summary> /// <param name="task"></param> private void StartDownload(OssTaskDO task) { //开启扫描 this.RefreshTask(); //是否需要创建文件 if (!File.Exists(task.DownloadPath + @"\" + task.DownloadName + ".download") || task.DownloadFileLength == 0) { //如果文件已经存在则删除 if (File.Exists(task.DownloadPath + @"\" + task.DownloadName + ".download")) { File.Delete(task.DownloadPath + @"\" + task.DownloadName + ".download"); } //读取线上文件信息 var ossPath = CheckOssPath(task.DownloadOssPath + @"\" + task.DownloadOssName); var fileInfo = client.GetObject(aliyunOSSConfig.BucketName, ossPath); task.DownloadFileLength = fileInfo.ContentLength; fileInfo.Dispose(); //智能分配碎片 if (task.DebrisSize <= 0) { task.DebrisSize = task.DownloadFileLength % 9999 == 0 ? task.DownloadFileLength / 9999 : task.DownloadFileLength / 9999 + 100; if (task.DebrisSize < task.MinDebrisSize) { task.DebrisSize = task.MinDebrisSize; } } //磁盘创建一个一样大小空文件 var fs = new FileStream(task.DownloadPath + @"\" + task.DownloadName + ".download", FileMode.Create); task.DownloadDebrisTotalCount = task.DownloadFileLength % task.DebrisSize == 0 ? task.DownloadFileLength / task.DebrisSize : task.DownloadFileLength / task.DebrisSize + 1; fs.Position = 0; for (int i = 1; i <= task.DownloadDebrisTotalCount; i++) { if (i == task.DownloadDebrisTotalCount) { var size = task.DownloadFileLength - task.DebrisSize * (i - 1); fs.Write(new byte[size], 0, (int)size); } else { fs.Write(new byte[task.DebrisSize], 0, (int)task.DebrisSize); } } task.Stream = fs; } else { task.Stream = new FileStream(task.DownloadPath + @"\" + task.DownloadName + ".download", FileMode.Open); } //存放Etag 读取Tag task.UploadETag = new List <string>(); var fileStream = new FileStream(task.DownloadPath + @"\" + task.DownloadName + ".download.config", FileMode.OpenOrCreate); fileStream.Position = 0; using (var readStream = new StreamReader(fileStream)) { while (true) { var row = readStream.ReadLine(); if (row == null) { break; } var values = row.Split(','); var id = values[0]; var index = task.UploadETag.FindIndex(r => r.Split(',')[0] == id); if (values.Length == 2 && index == -1) { task.UploadETag.Add(row); } else { Console.WriteLine("Read Tag: " + row + ", index:" + index); } } } //隐藏文件 File.SetAttributes(task.DownloadPath + @"\" + task.DownloadName + ".download.config", FileAttributes.Hidden); Console.WriteLine("Tag: " + task.UploadETag.Count); //在相同下载文件目录生成一个隐藏配置文件 fileStream = new FileStream(task.DownloadPath + @"\" + task.DownloadName + ".download.config", FileMode.OpenOrCreate); fileStream.Position = fileStream.Length; task.ConfigStream = new StreamWriter(fileStream); task.ConfigStream.AutoFlush = false; //创建碎片任务 task.DebrisProgress = new bool?[task.DownloadDebrisTotalCount]; for (int i = 0; i < task.DownloadDebrisTotalCount; i++) { var index = task.UploadETag.FindIndex(r => r.Split(',')[0] == i.ToString()); task.DebrisProgress[i] = index >= 0; } Console.WriteLine("Tag:" + task.UploadETag.Count); //总长度 task.Progress = task.UploadETag.Count * task.DebrisSize; task.TotalProgress = task.DownloadFileLength; //保存配置 SaveOssTaskConfig(taskList); //开启线程下载文件 task.ThreadList = new List <Task>(); task.ThreadTokenList = new List <CancellationTokenSource>(); task.ThreadTokenStatusList = new List <TokenStatus>(); for (int i = 0; i < threadCount; i++) { var token = new CancellationTokenSource(); task.ThreadList.Add(new Task(() => { for (; ;) { try { if (task.ThreadTokenStatusList == null) { return; } var taskStatus = task.ThreadTokenStatusList.Find(it => it.Token == token); if (taskStatus.Status) { return; } if (DownloadItem(task) == null) { return; } if (taskStatus.Status) { return; } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } }, token.Token)); task.ThreadTokenList.Add(token); task.ThreadTokenStatusList.Add(new TokenStatus { Token = token, Status = false }); } //等待任务完成结束 Task.WhenAll(task.ThreadList.ToArray()).ContinueWith(s => { DownloadComplete(task); }); //开始 task.ThreadList.ForEach(it => it.Start()); }
public static void getObjectBySignedUrl2() { const string accessKeyId = "<your access key id>"; const string accessKeySecret = "<your access key secret>"; const string endpoint = "<valid host name>"; const string bucketName = "<bucket name>"; const string key = "<object name>"; OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { var metadata = client.GetObjectMetadata(bucketName, key); var etag = metadata.ETag; var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get); // Generates url signature for accessing specified object. var uri = client.GeneratePresignedUri(req); Console.WriteLine(uri.ToString()); OssObject ossObject = client.GetObject(uri); var file = File.Open("<file to hold object content>", FileMode.OpenOrCreate); Stream stream = ossObject.Content; byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); file.Write(bytes, 0, bytes.Length); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } }
private void bw_DoWork(object sender, DoWorkEventArgs e) { alioss alioss = new alioss(SurveyMsg.OSSRegion, false, SurveyMsg.ProjectId); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); this.bw.ReportProgress(20, "检查更新....."); OssClient ossClient = new OssClient(alioss.endpoint, alioss.accessId, alioss.accessKey); bool flag = false; try { using (IEnumerator <Bucket> enumerator = ossClient.ListBuckets().GetEnumerator()) { while (enumerator.MoveNext()) { if (enumerator.Current.Name == alioss.bucketNameUpdate) { flag = true; break; } } } } catch (Exception) { this.bw.ReportProgress(90, GClass0.smethod_0("朤臰跒悮指垨偠ܫ菱懅淡瑒狞")); MessageBox.Show(GClass0.smethod_0("朤臰跒悮指垨偠菱懅淡瑒狞"), GClass0.smethod_0("牌是擶暱"), MessageBoxButton.OK, MessageBoxImage.Asterisk); stopwatch.Stop(); return; } if (!flag) { this.bw.ReportProgress(90, GClass0.smethod_0("孑冠攊冧剭壶规思")); MessageBox.Show(GClass0.smethod_0("孑冠攊冧剭壶规思"), GClass0.smethod_0("牌是擶暱"), MessageBoxButton.OK, MessageBoxImage.Asterisk); stopwatch.Stop(); return; } string str = ""; int num = this.VersionID.ToLower().IndexOf(GClass0.smethod_0("w")); if (num > -1) { str = this.VersionID.Substring(0, num); } else if (this.VersionID.IndexOf(GClass0.smethod_0("浈諗灉")) > -1) { str = GClass0.smethod_0("浈諗灉"); } else if (this.VersionID.IndexOf(GClass0.smethod_0("漗砸灉")) > -1) { str = GClass0.smethod_0("漗砸灉"); } else if (this.VersionID.IndexOf(GClass0.smethod_0("歠帍灉")) > -1) { str = GClass0.smethod_0("歠帍灉"); } else if (this.VersionID.IndexOf(GClass0.smethod_0("辆厫灉")) > -1) { str = GClass0.smethod_0("辆厫灉"); } ObjectListing objectListing = ossClient.ListObjects(alioss.bucketNameUpdate, alioss.bucketDirUpdate + GClass0.smethod_0(".") + str); if (objectListing.ObjectSummaries.Count <OssObjectSummary>() == 0) { this.bw.ReportProgress(90, GClass0.smethod_0("朣昁灏搪拱悴掄䧴")); MessageBox.Show(GClass0.smethod_0("朣昁灏搪拱悴掄䧴"), GClass0.smethod_0("牌是擶暱"), MessageBoxButton.OK, MessageBoxImage.Asterisk); stopwatch.Stop(); return; } string text = ""; string key = ""; string text2 = this.VersionID.ToLower(); string text3 = text2; string text4 = ""; foreach (OssObjectSummary ossObjectSummary in objectListing.ObjectSummaries) { if (!(ossObjectSummary.Key == alioss.bucketDirUpdate + GClass0.smethod_0("."))) { text = ossObjectSummary.Key.Replace(alioss.bucketDirUpdate + GClass0.smethod_0("."), ""); text4 = text.Replace(GClass0.smethod_0("*űɣͳ"), "").ToLower(); key = ossObjectSummary.Key; if (string.Compare(text4, text3) > 0) { text3 = text4; } } } if (text3 == text2) { this.bw.ReportProgress(90, GClass0.smethod_0("彙卄忺緈戩戅掴畋漮")); MessageBox.Show(GClass0.smethod_0("彙卄忺緈戩戅掴畋漮"), GClass0.smethod_0("牌是擶暱"), MessageBoxButton.OK, MessageBoxImage.Asterisk); stopwatch.Stop(); return; } string text5 = Environment.CurrentDirectory + GClass0.smethod_0("VōɧͰѨթ٫ݢࡦढ़"); if (!Directory.Exists(text5)) { Directory.CreateDirectory(text5); } if (!Directory.Exists(text5)) { this.bw.ReportProgress(90, GClass0.smethod_0("曱撴嬲踧ff")); MessageBox.Show(string.Concat(new string[] { GClass0.smethod_0("曤撿灆搡懺杋鄊躈續沀䓰刼䈉噛太"), Environment.NewLine, Environment.NewLine, GClass0.smethod_0("详嘸擻暾噀蓦蹇龎奁埲烌䗣䈎梃䃵嘻"), Environment.NewLine, text5 }), GClass0.smethod_0("曰撳嬳踤"), MessageBoxButton.OK, MessageBoxImage.Asterisk); stopwatch.Stop(); return; } RarFile rarFile = new RarFile(); string path = text5 + text; this.bw.ReportProgress(40, string.Format(GClass0.smethod_0("丂蹵枀䷰Хտسݿࠡ"), text)); FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read); GetObjectRequest getObjectRequest = new GetObjectRequest(alioss.bucketNameUpdate, key); ossClient.GetObject(getObjectRequest, fileStream); fileStream.Close(); this.bw.ReportProgress(80, string.Format(GClass0.smethod_0("觪劃枀䷰Хտسݿࠡ"), text)); this.strRarFile = path; this.strRarOutputFolder = Environment.CurrentDirectory + GClass0.smethod_0("]"); rarFile.Extract(this.strRarFile, this.strRarOutputFolder, this.strRarOutputFolder, this.strRarPassword); this.bw.ReportProgress(95, GClass0.smethod_0("牎昩擰暳䨸福") + text3); this.bw.ReportProgress(95, string.Format(GClass0.smethod_0("夊甋妀愛st蔞揾ܧࡽवଣ痐㴃"), stopwatch.Elapsed.TotalSeconds.ToString(GClass0.smethod_0("Dij")))); stopwatch.Stop(); }
public override Thread Create() { return(new Thread(() => { try { var endpoint = ConfigurationManager.AppSettings["Oss.Mangning.Url"]; var keyId = ConfigurationManager.AppSettings["Oss.Mangning.KeyId"]; var keySecret = ConfigurationManager.AppSettings["Oss.Mangning.KeySecret"]; var bucket = ConfigurationManager.AppSettings["Oss.Mangning.Bucket"]; var client = new OssClient(endpoint, keyId, keySecret); var total = 0; var count = 0; Task.Run(() => ListObject(client, bucket)); for (var i = 0; i < 16; i++) { Task.Run(() => { var stopwatch = new Stopwatch(); while (true) { string path; if (!fileQueue.TryDequeue(out path)) { Thread.Sleep(100); continue; } try { stopwatch.Restart(); int flag; int resumeId; using (var stream = new MemoryStream()) { var bytes = new byte[1024]; int len; var streamContent = client.GetObject(bucket, path).Content; while ((len = streamContent.Read(bytes, 0, bytes.Length)) > 0) { stream.Write(bytes, 0, len); } int.TryParse(Path.GetFileNameWithoutExtension(path), out resumeId); flag = FlagResume(Encoding.UTF8.GetString(GZip.Decompress(stream.ToArray())), resumeId, client, bucket); } stopwatch.Stop(); var elapsed = stopwatch.ElapsedMilliseconds; Interlocked.Increment(ref total); if (flag == 0xF) { Interlocked.Increment(ref count); } Console.WriteLine($"{DateTime.Now} > ResumeID = {resumeId}, Flag = {Convert.ToString(flag, 2).PadLeft(4, '0')}, Elapsed = {elapsed} ms, Count/Total = {count}/{total}."); } catch (Exception ex) { Trace.TraceError(ex.ToString()); } } }); } } catch (Exception ex) { Trace.TraceError(ex.ToString()); } }) { IsBackground = true }); }
private void button3_Click(object sender, EventArgs e) { show_log("开始扫描阿里oss\r\n"); timer1.Enabled = false; var client = new OssClient(endpoint, accessKeyId, accessKeySecret); var keys = new List <string>(); ObjectListing result = null; string nextMarker = string.Empty; string downloadFilename; string temdirname; int temint; string temdatestr, temkeydirstr; do { var listObjectsRequest = new ListObjectsRequest(bucketName) { Marker = nextMarker, MaxKeys = 1000, Prefix = prefix, }; result = client.ListObjects(listObjectsRequest); foreach (var summary in result.ObjectSummaries) { string str; int i; show_log("a--" + summary.Key + "\r\n"); str = summary.Key; i = str.IndexOf("SH"); if (i <= 0) { continue; } str = str.Substring(i, 15); if (!ispay(str)) { show_log(" 单号未付款:" + str + "\r\n"); continue; } else { show_log(" 单号以付款:" + str + "\r\n"); } keys.Add(summary.Key); if (summary.Size == 0) { show_log(" 删除summary.keuy:" + summary.Key + "\r\n"); client.DeleteObject(bucketName, summary.Key); continue; } var obj = client.GetObject(bucketName, summary.Key); using (var requestStream = obj.Content) { temkeydirstr = Path.GetDirectoryName(summary.Key); temint = temkeydirstr.IndexOf("\\") + 1; temdatestr = temkeydirstr.Substring(temint, 10); downloadFilename = downtodir + temdatestr + "\\" + temkeydirstr; // downloadFilename = downtodir + summary.Key; if (Directory.Exists(downloadFilename)) { } else { Directory.CreateDirectory(downloadFilename); } downloadFilename = downloadFilename + "\\" + Path.GetFileName(summary.Key); byte[] buf = new byte[1024]; var fs = File.Open(downloadFilename, FileMode.OpenOrCreate); var len = 0; // 通过输入流将文件的内容读取到文件或者内存中。 while ((len = requestStream.Read(buf, 0, 1024)) != 0) { fs.Write(buf, 0, len); } fs.Close(); } ///下载后,复制文件到down_ok目录 var req = new CopyObjectRequest(bucketName, summary.Key, downok_bucketName, summary.Key); client.CopyObject(req); client.DeleteObject(bucketName, summary.Key); show_log("Get object succeeded" + downloadFilename + "\r\n"); } nextMarker = result.NextMarker; } while (result.IsTruncated); timer1.Enabled = true; }
public Stream GetObject(string filename) { OssObject downfile = client.GetObject("offlinesales", filename); return(downfile.Content); }
public BaiYeMapItem GetMapInfoByGPS(string adr, double x, double y, bool usehpic, POI poi = null) { int xx = 0; var mapname = FindMap(y, x, out xx); if (string.IsNullOrEmpty(mapname)) { return(null); } _logger.LogInformation($"找到地图:{mapname}"); string ext = ".jpg"; long picq = 10L; if (mapname.Contains("上册")) { ext = ".jpeg"; picq = 50L; } if (usehpic) { picq = 80L; } //download file var fileobject = client.GetObject(_ossoption.BucketName, "MapData/" + mapname + ext); var image = Image.FromStream(fileobject.Content); Bitmap bmp = null; if (xx == 1) { bmp = Cut(image, 0, 0, image.Width / 2, image.Height); } else if (xx == 2) { bmp = Cut(image, image.Width / 2, 0, image.Width / 2, image.Height); } else if (xx == 3) { bmp = Cut(image, image.Width / 2, 0, image.Width / 2, image.Height); } else if (xx == 4) { bmp = Cut(image, 0, 0, image.Width / 2, image.Height); } else { return(null); } _logger.LogInformation($"找到地图部分:{xx}(1左2右3左4右)"); var key = (mapname + ':' + xx.ToString()).GetHashCode().ToString(); var url = GenPicFromOSS(key, ext, picq, bmp); BaiYeMapItem item = new BaiYeMapItem(); item.Name = adr; item.TmpPicUrl = url; item.GpsLng = x; item.GpsLat = y; item.POIKey = poi == null?0:poi.id; _logger.LogInformation($"地图图片:{url}"); return(item); }
public OssObject GetObject(string bucketName, string key) { return(_ossClient.GetObject(bucketName, key)); }
public void _DownLoadFile(object value) { OssObject ossobject = null; GetObjectRequest request = null; ObjectMetadata metadata; FileStream fs = null; int readline = 0; //当前读取的字节长度 long countlength = 0; //已经读取的字节 byte[] buffer = new byte[length]; //文件块 string bucket = "", fileKey = "", targetPath = ""; if (value is string[]) { bucket = ((string[])value)[0]; fileKey = ((string[])value)[1]; targetPath = ((string[])value)[2]; } else { return; } if (File.Exists(targetPath)) { try { File.Delete(targetPath); } catch (IOException ioEx) //文件正在使用中,不能删除。 { return; } } fs = new FileStream(targetPath, FileMode.Create); try { request = new Aliyun.OpenServices.OpenStorageService.GetObjectRequest(bucket, fileKey); ossobject = client.GetObject(request);//获取文件流 //获取需要下载文件的信息。 metadata = client.GetObjectMetadata(bucket, fileKey); while ((readline = ossobject.Content.Read(buffer, 0, length)) > 0) { fs.Write(buffer, 0, readline); countlength += readline; if (DownLoadProcessing != null) { DownLoadProcessing(Convert.ToDouble(countlength) / Convert.ToDouble(metadata.ContentLength)); } } } catch (Aliyun.OpenServices.ServiceException serviceEx) //下载过程中出现错误。 { } finally { ossobject.Dispose(); fs.Close(); } }
public void Buquan() { var queue = new ConcurrentQueue <KeyValuePair <int, KeyValuePair <string, DateTime> > >(); var index = 0; Task.Run(() => { while (true) { KeyValuePair <int, KeyValuePair <string, DateTime> > temp; if (!queue.TryDequeue(out temp)) { Thread.Sleep(10); continue; } using (var db = new MangningXssDBEntities()) { var resume = db.ZhaopinResume.FirstOrDefault(f => f.Id == temp.Key); if (resume == null) { LogFactory.Warn($"找不到简历 ResumeId =>{temp.Key}"); continue; } var user = db.ZhaopinUser.FirstOrDefault(f => f.Id == resume.UserId); if (user == null) { LogFactory.Warn($"找不到用户 ResumeId =>{temp.Key} UserId =>{resume.UserId}"); continue; } if (string.IsNullOrEmpty(temp.Value.Key) && string.IsNullOrEmpty(user.Cellphone)) { db.ZhaopinResume.Remove(resume); db.ZhaopinUser.Remove(user); Console.WriteLine($"删除成功!ResumeId=>{temp.Key} {++index}/{buquanTotal}"); } else { resume.UserExtId = temp.Value.Key; user.CreateTime = temp.Value.Value; Console.WriteLine($"补全成功!{++index}/{buquanTotal}"); } db.SaveChanges(); } } }); using (var db = new MangningXssDBEntities()) { var idArray = db.ZhaopinResume.Where(w => w.Source == "Watch").Select(s => s.Id).ToArray(); buquanTotal = idArray.Length; foreach (var businessId in idArray) { try { var streamContent = newOss.GetObject(newBucket, $"WatchResume/{businessId}").Content; using (var stream = new MemoryStream()) { var bytes = new byte[1024]; int len; while ((len = streamContent.Read(bytes, 0, bytes.Length)) > 0) { stream.Write(bytes, 0, len); } var jsonContent = Encoding.UTF8.GetString(GZip.Decompress(stream.ToArray())); var resumeData = JsonConvert.DeserializeObject <dynamic>(jsonContent); var resumeDetail = JsonConvert.DeserializeObject <dynamic>((string)resumeData.detialJSonStr); var createDate = BaseFanctory.GetTime((string)resumeDetail.DateCreated).ToUniversalTime(); var extId = resumeDetail.UserMasterExtId.ToString(); queue.Enqueue(new KeyValuePair <int, KeyValuePair <string, DateTime> >(businessId, new KeyValuePair <string, DateTime>(extId, createDate))); } } catch (Exception ex) { LogFactory.Warn($"Oss 获取简历异常! ResumeId => {businessId} 异常原因 => {ex.Message}"); queue.Enqueue(new KeyValuePair <int, KeyValuePair <string, DateTime> >(businessId, new KeyValuePair <string, DateTime>("", DateTime.Now))); } } } }
public ActionResult GetFile(int id, int width = 0, int height = 0) { int bfid = id; BLLBFInfo bllbfinfo = new BLLBFInfo(); var bfinfo = bllbfinfo.Find(bfid); if (bfinfo == null) { return Content("不存在的数据"); } else { bfinfo.LastViewDateTime = DateTime.Now; bfinfo.GetCount++; bllbfinfo.UpDate(bfinfo); //返回一个二进制流!根据类型,来判断,需要返回的内容! MemoryStream ms = new MemoryStream(); OssClient oc = new OssClient(AccessKeyID, AccessKeySecret); GetObjectRequest getObjectRequest = new GetObjectRequest(BucketName, bfinfo.OSSFileName); oc.GetObject(getObjectRequest, ms); if (bfinfo.MineType.Contains("image")) { if (width == 0 && height == 0) { return File(ms.ToArray(), bfinfo.MineType); } else { Image image = System.Drawing.Image.FromStream(ms); return File(GetThumbnail(image, width, height).ToArray(), bfinfo.MineType); } } else { return File(ms.ToArray(), bfinfo.MineType); } } }