本文整理汇总了C#中System.Net.WebClient.OpenWrite方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.OpenWrite方法的具体用法?C# WebClient.OpenWrite怎么用?C# WebClient.OpenWrite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.WebClient
的用法示例。
在下文中一共展示了WebClient.OpenWrite方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: OnBeginRequest_Should_Compress_Whitespace
public void OnBeginRequest_Should_Compress_Whitespace()
{
//arrange
_httpRequest.SetupGet(request => request.Url).Returns(new Uri("http://www.mysite.com/"));
_httpRequest.SetupGet(request => request.RawUrl).Returns("http://www.mysite.com/default.aspx");
_httpRequest.SetupGet(request => request.Headers)
.Returns(new NameValueCollection {{"Accept-Encoding", "Gzip"}});
using (var client = new WebClient())
{
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
_httpResponse.SetupGet(response => response.Filter).Returns(client.OpenWrite("http://www.hao123.net"));
}
_httpCachePolicy.SetupGet(hc => hc.VaryByHeaders).Returns(new HttpCacheVaryByHeaders());
_httpResponse.SetupGet(response => response.Cache).Returns(_httpCachePolicy.Object);
// act
var module = new CompressWhitespaceModule();
module.OnBeginRequest(_httpContext.Object);
//assert
_httpResponse.VerifyAll();
}
示例2: Form1
public Form1()
{
InitializeComponent();
WebClient client = new WebClient();
Stream stream1 = client.OpenRead("http://www.baidu.cn");
StreamReader sr = new StreamReader(stream1);
string line;
while ((line = sr.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
stream1.Close();
try
{
Stream stream2 = client.OpenWrite("http://localhost/accept/newfile.txt", "PUT");
StreamWriter sw = new StreamWriter(stream2);
sw.WriteLine("Hello Web");
stream2.Close();
}
catch (System.Exception)
{
}
//异步加载WebRequest
WebRequest wr = WebRequest.Create("http://www.reuters.com");
wr.BeginGetResponse(new AsyncCallback(OnResponse), wr);
}
示例3: SendMessage
public void SendMessage(Lamp lampState)
{
WebClient webClient = new WebClient();
webClient.BaseAddress = "http://" + bridgeIP + "/api/" + username + "/lights/" + lampState.GetLampNumber() + "/state";
Stream writeData = webClient.OpenWrite(webClient.BaseAddress, "PUT");
writeData.Write(Encoding.ASCII.GetBytes(lampState.GetJson()), 0, lampState.GetJson().Length);
writeData.Close();
}
示例4: UploadFile
public static bool UploadFile(string localFilePath, string serverFolder, bool reName)
{
string fileNameExt, newFileName, uriString;
if (reName)
{
fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf(".") + 1);
newFileName = DateTime.Now.ToString("yyMMddhhmmss") + fileNameExt;
}
else
{
newFileName = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);
}
if (!serverFolder.EndsWith("/") && !serverFolder.EndsWith("\\"))
{
serverFolder = serverFolder + "/";
}
uriString = serverFolder + newFileName; //服务器保存路径
/**/
/// 创建WebClient实例
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
// 要上传的文件
FileStream fs = new FileStream(newFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
//FileStream fs = new FileStream(newFileName, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
try
{
//使用UploadFile方法可以用下面的格式
//myWebClient.UploadFile(uriString,"PUT",localFilePath);
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
}
else
{
MessageBox.Show("文件目前不可写!");
}
postStream.Close();
}
catch
{
//MessageBox.Show("文件上传失败,请稍候重试~");
return false;
}
return true;
}
示例5: PostFood
static void PostFood(Food food)
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var uri = new Uri("http://localhost:3401/api/foodapi/");
using (var stream = client.OpenWrite(uri, "POST"))
{
var serializer = new DataContractJsonSerializer(typeof(Food));
serializer.WriteObject(stream, food);
stream.Close();
}
}
}
示例6: Main
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
WebClient webClient = new WebClient();
try
{
Stream stream = webClient.OpenWrite("http://localhost/accept/newfile.txt","PUT");
StreamWriter streamWriter = new StreamWriter(stream);
streamWriter.WriteLine("Hello there, World....");
streamWriter.Close();
}
catch (Exception e) {Console.WriteLine( e.ToString() ); }
Console.ReadLine();
}
示例7: UpLoadFile
public void UpLoadFile(string fileNamePath)
{
/// 创建WebClient实例
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
// 要上传的文件
FileStream fs = new FileStream("C:\\1.zip", FileMode.Open, FileAccess.Read);
//FileStream fs = OpenFile();
BinaryReader r = new BinaryReader(fs);
byte[] postArray = r.ReadBytes((int)fs.Length);
//Stream postStream = myWebClient.OpenWrite(FileName, "PUT");
//Stream postStream = myWebClient.OpenWrite("~/Upload/" + FileName, "PUT");
//C:\文档资料\自动化测试平台\ATP20140629\ATP\Upload
Stream postStream = myWebClient.OpenWrite("C:\\" + FileName, "PUT");
try
{
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
postStream.Close();
fs.Dispose();
}
else
{
postStream.Close();
fs.Dispose();
}
}
catch (Exception err)
{
postStream.Close();
fs.Dispose();
throw err;
}
finally
{
postStream.Close();
fs.Dispose();
}
}
示例8: OpenWrite
/// <summary>
/// Returns a stream for writing to the source
/// </summary>
/// <returns></returns>
public static Stream OpenWrite(this BlobImportSource source)
{
if (string.IsNullOrEmpty(source.ConnectionString))
{
var client = new WebClient();
var rawStream = client.OpenWrite(source.BlobUri);
return source.IsGZiped ? new GZipStream(rawStream, CompressionMode.Compress) : rawStream;
}
else
{
CloudStorageAccount storageAccount;
if (!CloudStorageAccount.TryParse(source.ConnectionString, out storageAccount))
{
throw new Exception("Invalid blob storage connection string");
}
var blobClient = storageAccount.CreateCloudBlobClient();
var blob = blobClient.GetBlobReference(source.BlobUri);
var rawStream = (Stream)blob.OpenWrite();
return source.IsGZiped ? new GZipStream(rawStream, CompressionMode.Compress) : rawStream;
}
}
示例9: Main
static void Main(string[] args)
{
//создание объекта web-клиент
WebClient client= new WebClient();
string TextToUpload = "User=Vasia&passwd=okna", urlString = "http://localhost/";
// Преобразуем текст в массив байтов
byte[] uploadData=Encoding.ASCII.GetBytes(TextToUpload);
// связываем URL с потоком записи
Stream upload=client.OpenWrite(urlString,"POST");
// загружаем данные на сервер
upload.Write(uploadData,0,uploadData.Length);
upload.Close();
WebClient clientUp= new WebClient();
//WebClient client= new WebClient();
clientUp.Credentials = System.Net.CredentialCache.DefaultCredentials;
// добавляем HTTP-заголовок
clientUp.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// Преобразуем текст в массив байтов
// копируем данные методом GET
byte[] respText=client.UploadData(urlString,"GET",uploadData);
// загружаем данные на сервер
upload.Write(uploadData,0,uploadData.Length);
upload.Close();
}
示例10: GetStreamCore
protected override Stream GetStreamCore(FileAccess access)
{
using (WebClient client = new WebClient()) {
WebRequest request = WebRequest.CreateDefault(this.Uri);
WebResponse response = request.GetResponse();
try {
this.cacheEncoding = Utility.GetEncodingFromContentType(response.ContentType);
} catch (NotSupportedException) {
this.cacheEncoding = null;
}
switch (access) {
case FileAccess.Read:
return client.OpenRead(this.uri);
case FileAccess.Write:
return client.OpenWrite(this.uri);
case FileAccess.ReadWrite:
default:
return client.OpenWrite(this.uri);
}
}
}
示例11: Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
Text += " " + GetLocalIPv4(NetworkInterfaceType.Ethernet);
Task.Factory.StartNew(() =>
{
UdpClient client = new UdpClient();
IPEndPoint localEp = new IPEndPoint(IPAddress.Any, Constants.MulticastPort);
client.Client.Bind(localEp);
IPAddress multicastaddress = IPAddress.Parse(Constants.MulticastAddress);
client.JoinMulticastGroup(multicastaddress);
Stopwatch sw = Stopwatch.StartNew();
int receivedCount = 0;
List<long> elapsedMicrosecs = new List<long>();
int lastIntData = -1;
int outOfOrderCount = 0;
while (receivedCount < Constants.RepeatCount)
{
Byte[] data = client.Receive(ref localEp);
string strData = Encoding.Unicode.GetString(data);
int intData = int.Parse(strData);
if (lastIntData != (intData - 1))
{
outOfOrderCount++;
}
lastIntData = intData;
if (receivedCount == 0)
sw.Restart();
elapsedMicrosecs.Add(sw.ElapsedMicroSeconds());
receivedCount++;
//Debug.WriteLine(strData);
//Debug.WriteLine(strData);
//Debug.WriteLine(sw.ElapsedMicroSeconds());
}
long[] timesBetween = elapsedMicrosecs.Select((el, idx) =>
{
if (idx == 0)
return Constants.IntervalMsec * 1000;
return el - elapsedMicrosecs[idx - 1];
}).ToArray();
int intervalMicroSec = Constants.IntervalMsec * 1000;
string msg = string.Format(@"Avg:{0}
StdDev:{1}
Min:{2}
Max:{3}
%({5}-{6}):{4}
OutOfOrder:{7}",
timesBetween.Average(),
timesBetween.StdDev(),
timesBetween.Min(),
timesBetween.Max(),
timesBetween.Count(tb => tb < (intervalMicroSec+100) && tb > (intervalMicroSec-100)) / (double)Constants.RepeatCount,
intervalMicroSec-100,
intervalMicroSec+100,
outOfOrderCount);
textBox1.Invoke(new Action( () => textBox1.Text = msg ));
ClientData clientData = new ClientData()
{
IpAddress = GetLocalIPv4(NetworkInterfaceType.Ethernet),
Avg = timesBetween.Average(),
StdDev = timesBetween.StdDev(),
Min = timesBetween.Min(),
Max = timesBetween.Max(),
PercWithinDelta = timesBetween.Count(tb => tb < (intervalMicroSec + 100) && tb > (intervalMicroSec - 100)) / (double)Constants.RepeatCount,
OutOfOrder = outOfOrderCount
};
WebClient wc = new WebClient();
XmlSerializer serializer = new XmlSerializer(typeof(ClientData));
using (StreamWriter streamWriter = new StreamWriter(wc.OpenWrite(Constants.ClientDataUrl)))
{
serializer.Serialize(streamWriter, clientData);
}
});
}
示例12: UploadFile
//public MyFile WriteVideoFile(string FileName, Stream FileContent, string Parentid, string UserToken)
//{
// Video createdVideo;
// try
// {
// Video newVideo = new Video();
// newVideo.Title = FileName;
// newVideo.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema));
// newVideo.Keywords = FileName;
// newVideo.Description = "My description";
// newVideo.YouTubeEntry.Private = false;
// newVideo.Tags.Add(new MediaCategory("mydevtag, anotherdevtag",
// YouTubeNameTable.DeveloperTagSchema));
// newVideo.YouTubeEntry.Location = new GeoRssWhere(37, -122);
// // alternatively, you could just specify a descriptive string
// // newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA");
// newVideo.YouTubeEntry.MediaSource = new MediaFileSource(FileContent, "test file",
// "video/quicktime");
// createdVideo = CreateRequest().Upload(newVideo);
// }
// catch (Exception ex)
// {
// return null;
// }
// ResourceToken objToken = objClient.CreateVideoFile("File", FileName,"", createdVideo.VideoId, UserToken);
// objClient.SetWriteSuccess(objToken.ContentId, UserToken);
// FileInfo objInfo = new FileInfo(FileName);
// Dictionary<string, string> DicProperties = new Dictionary<string, string>();
// DicProperties.Add("Name", objInfo.Name);
// MyFile file = objClient.AddFile(objToken.ContentId, FileName, Parentid, Enums.contenttype.video.ToString(),JsonConvert.SerializeObject(DicProperties), UserToken);
// return file;
//}
//Here Response Means Pass the "Page.Response"\
//chk
//public void ReadFile(string RelationId, string UserToken, HttpResponse Response)
//{
// ResourceToken RToken = objClient.GetReadFile(RelationId, UserToken);
// DownloadFile(RToken.Url, RToken.Filename, Response);
//}
private bool UploadFile(Stream fileStream, string Url,string contentType)
{
try
{
//Create weClient
WebClient c = new WebClient();
//add header
c.Headers.Add("Content-Type",contentType);
//Create Streams
Stream outs = c.OpenWrite(Url, "PUT");
Stream ins = fileStream;
CopyStream(ins, outs);
ins.Close();
outs.Flush();
outs.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
示例13: UploadFile
/// <summary>
/// web�ļ��ϴ�
/// </summary>
/// <param name="WebURI">�ļ��ϴ������ַ</param>
/// <param name="LocalFile">�����ϴ��ļ���·��</param>
/// <param name="userName">�����û���</param>
/// <param name="password">����</param>
/// <param name="domain">����</param>
/// <param name="isMD5file">�ļ����Ƿ�Ҫ����MD5�㷨��ȡ</param>
public void UploadFile(string webURI, string localFile, string userName, string password, string domain, bool isMD5file)
{
try
{
// Local Directory File Info
if (!System.IO.File.Exists(localFile))//����ļ�������
{
if (this.fileTransmitError != null)
this.fileTransmitError(this, new fileTransmitEvnetArgs(true, localFile, localFile, "Ҫ�ϴ����ļ������ڣ���ȷ���ļ�·���Ƿ���ȷ��", 0, 0, this.FileMD5Value));
return;
}
System.IO.FileInfo fInfo = new FileInfo(localFile);//��ȡ�ļ�����Ϣ
if (isMD5file)//�����Ҫ���ļ�MD5,��ִ��MD5
webURI += "\\" + CSS.IM.Library.Class.Hasher.GetMD5Hash(localFile) + fInfo.Extension;//��ȡ�ļ���MD5ֵ
else
webURI += "\\" + fInfo.Name;// +fInfo.Extension;//��ȡ�ļ���MD5ֵ
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
this.netCre = new NetworkCredential(userName, password, domain);
myWebClient.Credentials = this.netCre;
if (getDownloadFileLen(webURI) == fInfo.Length)//������������Ѿ��д��ļ��������˳�
{
if (this.fileTransmitted != null)
this.fileTransmitted(this, new fileTransmitEvnetArgs(true, localFile, fInfo.Name, "", Convert.ToInt32(fInfo.Length), Convert.ToInt32(fInfo.Length), this.FileMD5Value));
return;
}
else
{
Stream postStream = myWebClient.OpenWrite(webURI, "PUT");
if (postStream.CanWrite)
{
byte[] FileBlock;
int readFileCount = 0;//���ļ�����
int maxReadWriteFileBlock = 1024 * 5;//һ�ζ��ļ�5k
long offset = 0;
readFileCount = (int)fInfo.Length / maxReadWriteFileBlock;//����ļ���д����
if ((int)fInfo.Length % maxReadWriteFileBlock != 0)
readFileCount++;//�����д�ļ����࣬�����д������1
for (int i = 0; i < readFileCount; i++)
{ //�����Ƕ�һ���ļ����ڴ����
if (i + 1 == readFileCount)//��������һ�ζ�д�ļ����������ļ�β����ȫ�����뵽�ڴ�
FileBlock = new byte[(int)fInfo.Length - i * maxReadWriteFileBlock];
else
FileBlock = new byte[maxReadWriteFileBlock];
////////////////////////�ļ�����
FileStream fw = new FileStream(localFile, FileMode.Open, FileAccess.Read, FileShare.Read);
offset = i * maxReadWriteFileBlock;
fw.Seek(offset, SeekOrigin.Begin);//�ϴη��͵�λ��
fw.Read(FileBlock, 0, FileBlock.Length);
fw.Close();
fw.Dispose();
///////////////////////////
postStream.Write(FileBlock, 0, FileBlock.Length);
if (this.fileTransmitting != null)
this.fileTransmitting(this, new fileTransmitEvnetArgs(true, localFile, fInfo.Name, "", Convert.ToInt32(fInfo.Length), (int)offset + FileBlock.Length, this.FileMD5Value));
}
}
postStream.Close();
myWebClient.Dispose();
}
if (this.fileTransmitted != null)
this.fileTransmitted(this, new fileTransmitEvnetArgs(true, localFile, fInfo.Name, "", Convert.ToInt32(fInfo.Length), Convert.ToInt32(fInfo.Length), this.FileMD5Value));
}
catch (Exception ex)
{
if (this.fileTransmitError != null)
this.fileTransmitError(this, new fileTransmitEvnetArgs(true, localFile, localFile, ex.Message + ex.Source, 0, 0, this.FileMD5Value));
}
}
示例14: SendFiles
public void SendFiles()
{
char[] ch = new char[1];
ch[0] = '/';
string[] arrstr = this.filestr.Split(ch);
WebClient myWebClient = new WebClient();
#region 做一存取凭据
//NetworkCredential myCred = new NetworkCredential("Administrator","11");//
//CredentialCache myCache = new CredentialCache();
//myCache.Add(new Uri(this.uri), "Basic", myCred);
//myWebClient.Credentials =myCache;
#endregion
//使用默认的权限
myWebClient.Credentials = CredentialCache.DefaultCredentials;
int count = this.listBox1.Items.Count;
this.progressBar1.Maximum = 10 * count;
for (int i = 0; i < arrstr.Length; i++)
{
try
{
string fileNamePath = arrstr[i];
string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
string uriString = this.uri + "/" + this.serverfolder + "/" + fileName;//指定上传得路径
// 要上传的文件
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
//FileStream fs = OpenFile();
BinaryReader r = new BinaryReader(fs);
//使用UploadFile方法可以用下面的格式
// myWebClient.UploadFile(uriString,"PUT",fileNamePath);
// MessageBox.Show(uriString);
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
this.progressBar1.Value = (i + 1) * 10;
}
else
{
MessageBox.Show("文件目前不可写!");
}
postStream.Close();
}
catch (WebException errMsg)
{
MessageBox.Show("上传失败:" + errMsg.Message);
break;
}
}
if (this.progressBar1.Value == this.progressBar1.Maximum)
{
MessageBox.Show("成功");
}
else
{
MessageBox.Show("传送中出现错误!");
}
}
示例15: TestOpenWriteWithInvalidMethod
public void TestOpenWriteWithInvalidMethod()
{
using (var server = InitializeFetchServer()) {
using (var client = new System.Net.WebClient()) {
try {
client.OpenWrite(new Uri(string.Format("imap://{0}/", server.HostPort)), ImapWebRequestMethods.Lsub);
Assert.Fail("WebException not thrown");
}
catch (WebException ex) {
Assert.IsInstanceOfType(typeof(NotSupportedException), ex.InnerException);
}
try {
client.OpenWrite(new Uri(string.Format("imap://{0}/INBOX", server.HostPort)), ImapWebRequestMethods.Subscribe);
Assert.Fail("WebException not thrown");
}
catch (WebException ex) {
Assert.IsInstanceOfType(typeof(ProtocolViolationException), ex.InnerException);
}
try {
client.OpenWrite(new Uri(string.Format("imap://{0}/INBOX/;UID=1", server.HostPort)), ImapWebRequestMethods.Fetch);
Assert.Fail("WebException not thrown");
}
catch (WebException ex) {
Assert.IsInstanceOfType(typeof(NotSupportedException), ex.InnerException);
}
try {
client.OpenWrite(new Uri(string.Format("imap://{0}/INBOX?UID 1", server.HostPort)), ImapWebRequestMethods.Search);
Assert.Fail("WebException not thrown");
}
catch (WebException ex) {
Assert.IsInstanceOfType(typeof(NotSupportedException), ex.InnerException);
}
}
}
}