⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileuploadthread.cs

📁 ASP C#代码实例 适合初学人士学习使用
💻 CS
字号:
using System;
using System.IO;
using System.Threading;

namespace Example_12_9
{
	/// <summary>
	/// FileUploadThread 的摘要说明。
	/// This class is used to craete new thread to upload a file
	/// </summary>
	public class FileUploadThread
	{
		private long _bytesRead;
		private Thread _tID;
		private string _filename;
		private Stream _stream;
		private bool _uploaded;
		private Exception _exception;

		/// <summary>
		/// How many bytes has been uploaded.
		/// </summary>
		public long BytesRead { get { return _bytesRead; } }
		
		/// <summary>
		/// Length of data to upload
		/// </summary>
		public long Length { get { return _stream.Length; } }
		
		/// <summary>
		/// Determine upload was finished
		/// </summary>
		public bool Uploaded { get { return _uploaded; } }
		
		/// <summary>
		/// How many percent has been uploaded
		/// </summary>
		public int Percent { get { return (int) ((BytesRead * 100) / Length); } }

		/// <summary>
		/// Exception object, is there was an exception, otherwise: null.
		/// </summary>
		public Exception Exception { get { return _exception; } }

		/// <summary>
		/// Class contructor.
		/// Initialize fields and create uploading thread.
		/// </summary>
		/// <param name="filename">File's name, with the path, to save</param>
		/// <param name="stream">Upload data's stream (ex. .PostedFile.InputStream)</param>
		public FileUploadThread(string filename, Stream stream)
		{
			_filename = filename;
			_stream = stream;
			_uploaded = false;
			_exception = null;

			_tID = new Thread(new ThreadStart(uploadThread) );
			_tID.Start();
		}

		/// <summary>
		/// Cancel upload's
		/// </summary>
		public void Cancel()
		{
			_tID.Abort();
		}

		/// <summary>
		/// Main thread procedure
		/// </summary>
		private void uploadThread()
		{
			byte[] b = new byte[1024];
			int read = 0;

			try
			{
				using (FileStream fs = new FileStream(_filename, FileMode.Create))
				{
					while ((read = _stream.Read(b, 0, b.Length)) > 0)
					{
						fs.Write(b, 0, read);
						_bytesRead += read;
						System.Threading.Thread.Sleep(100);
					}
				}
			}
			catch (Exception ex)
			{
				_exception = ex;
			}
			_uploaded = true;
		}	
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -