Example #1
0
        public bool Put(string file, byte[] data)
        {
            if (file[0] != '/')
            {
                file = "/" + file;
            }
            var       sign      = GetSignature("put", file);
            string    url       = Host + file;
            WebClient webClient = new WebClient();

            webClient.Headers.Add("Authorization", sign);
            webClient.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                Stream postStream = webClient.OpenWrite(url, "PUT");
                postStream.Write(data, 0, data.Length);
                postStream.Close();
            }
            catch (WebException webError)
            {
                string errorText;
                using (System.IO.StreamReader reader = new StreamReader(webError.Response.GetResponseStream()))
                {
                    errorText = reader.ReadToEnd();
                }
                throw new Exception(errorText, webError);
            }
            return(true);
        }
Example #2
0
        public bool UploadFile(string fileUrl, string fileName)
        {
            if (string.IsNullOrEmpty(fileUrl) || string.IsNullOrEmpty(fileName))
            {
                return(false);
            }
            WebClient client = new WebClient {
                Credentials = this.credentialCache_0
            };
            int count = 0;

            byte[] buffer = null;
            using (Stream stream = client.OpenRead(fileUrl))
            {
                count  = (int)stream.Length;
                buffer = new byte[count];
                stream.Read(buffer, 0, count);
            }
            try
            {
                string address = this.method_0(this.string_0, fileName);
                using (Stream stream2 = client.OpenWrite(address, "PUT"))
                {
                    stream2.Write(buffer, 0, count);
                }
            }
            catch (WebException)
            {
                return(false);
            }
            return(true);
        }
Example #3
0
 private void AccountPresenceStatusChanged(ISipAccount account)
 {
     if (_isActive && account.PresenceStatus.Code == _targetState)
     {
         try
         {
             var uri = _substFunc(_uri, account);
             using (var client = new WebClient {
                 CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore), Proxy = _proxy
             })
             {
                 if ("GET".Equals(_httpMethod, StringComparison.InvariantCultureIgnoreCase))
                 {
                     client.DownloadString(uri);
                 }
                 else
                 {
                     using (var stream = client.OpenWrite(uri, _httpMethod))
                     {
                         stream.Flush();
                     }
                 }
             }
         }
         catch (Exception e)
         {
             Logger.LogWarn(e, "Error sending state update");
         }
     }
     else
     {
         _isActive = true;
     }
 }
Example #4
0
        /// <summary>
        /// 上传照片
        /// </summary>
        /// <param name="uri">上传地址</param>
        /// <param name="path">本地文件路径</param>
        /// <returns></returns>
        public static string UpLoad_Image(string uri, string path)
        {
            //@" http://localhost:1111/"
            string result = string.Empty;

            if (File.Exists(path))
            {
                WebClient    wc       = new WebClient();
                string       fileName = Guid.NewGuid().ToString().Replace("-", "") + path.Substring(path.LastIndexOf("."));
                FileStream   fs       = new FileStream(path, FileMode.Open, FileAccess.Read);
                BinaryReader br       = new BinaryReader(fs);
                try
                {
                    byte[] postArray  = br.ReadBytes((int)fs.Length);
                    Uri    u          = new Uri(uri + fileName + ".abc");
                    Stream postStream = wc.OpenWrite(u, "POST");
                    if (postStream.CanWrite)
                    {
                        postStream.Write(postArray, 0, postArray.Length);
                    }
                    else
                    {
                    }
                    postStream.Close();
                }
                catch (WebException errMsg)
                {
                }
                result = FileDownloadWebSite + fileName;
            }

            return(result);
        }
Example #5
0
 private static void FlushBatch(string instanceUrl, List <JObject> batch)
 {
     using (var webClient = new WebClient())
     {
         webClient.UseDefaultCredentials = true;
         webClient.Credentials           = CredentialCache.DefaultNetworkCredentials;
         using (var stream = webClient.OpenWrite(instanceUrl + "bulk_docs", "POST"))
             using (var streamWriter = new StreamWriter(stream))
                 using (var jsonTextWriter = new JsonTextWriter(streamWriter))
                 {
                     var commands = new JArray();
                     foreach (var doc in batch)
                     {
                         var metadata = doc.Value <JObject>("@metadata");
                         doc.Remove("@metadata");
                         commands.Add(new JObject(
                                          new JProperty("Method", "PUT"),
                                          new JProperty("Document", doc),
                                          new JProperty("Metadata", metadata),
                                          new JProperty("Key", metadata.Value <string>("@id"))
                                          ));
                     }
                     commands.WriteTo(jsonTextWriter);
                     jsonTextWriter.Flush();
                     streamWriter.Flush();
                 }
     }
     batch.Clear();
 }
Example #6
0
        /// <summary>
        /// Set permission of a path.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="permissions"></param>
        public bool SetPermissions(string path, string permissions)
        {
            WebClient hc = this.CreateHTTPClient();

            hc.OpenWrite(this.GetUriForOperation(path) + "op=SETPERMISSION&permission=" + permissions, "PUT");
            return(true);
        }
Example #7
0
        /// <summary>
        /// Set modification time of a file
        /// </summary>
        /// <param name="path"></param>
        /// <param name="modificationTime">Set the modification time of this file. The number of milliseconds since Jan 1, 1970.
        /// A value of -1 means that this call should not set modification time</param>
        public bool SetModificationTime(string path, string modificationTime)
        {
            WebClient hc = this.CreateHTTPClient();

            hc.OpenWrite(this.GetUriForOperation(path) + "op=SETTIMES&modificationtime=" + modificationTime, "PUT");
            return(true);
        }
Example #8
0
        /// <summary>
        /// Send mail to developers via CT2 DEVMAIL web interface.
        /// Server-side spam protection is not handled differently from other server errors.
        /// </summary>
        /// <exception cref="SpamException">Thrown when client-side spam protection triggers</exception>
        /// <param name="action">Either DEVMAIL or TICKET</param>
        /// <param name="title">Subject (without any "CrypTool" prefixes, will be added at server-side)</param>
        /// <param name="text">Message body</param>
        /// <param name="sender">Mail from (optional)</param>
        public static void SendMailToCoreDevs(string action, string title, string text, string sender = null)
        {
            // Client-side spam check. Will fail if client changes system time.
            TimeSpan diff = DateTime.Now - lastMailTime;

            if (diff < TimeSpan.FromSeconds(MINIMUM_DIFF))
            {
                // +1 to avoid confusing "0 seconds" text message
                throw new SpamException(string.Format(Properties.Resources.Please_wait_seconds_before_trying_again, Math.Round(MINIMUM_DIFF - diff.TotalSeconds + 1)));
            }

            var client = new WebClient();

            client.Headers["User-Agent"] = "CrypTool";
            var stream = client.OpenWrite("http://www.cryptool.org/cgi/ct2devmail");

            string postMessage = string.Format("action={0}&title={1}&text={2}", Uri.EscapeDataString(action), Uri.EscapeDataString(title), Uri.EscapeDataString(text));

            if (!string.IsNullOrWhiteSpace(sender))
            {
                postMessage += string.Format("&sender={0}", Uri.EscapeDataString(sender));
            }

            var postEncoded = Encoding.ASCII.GetBytes(postMessage);

            stream.Write(postEncoded, 0, postEncoded.Length);
            stream.Close();

            client.Dispose();

            lastMailTime = DateTime.Now;
        }
Example #9
0
        private void SendPartialPattern(string path, IPattern pattern)
        {
            try
            {
                using (WebClient wc = new WebClient {
                    BaseAddress = this.baseAddress
                })
                    using (Stream stream = wc.OpenWrite(path, HttpMethod.Post))
                        using (XmlWriter writer = XmlWriter.Create(stream))
                        {
                            writer.WriteStartDocument();
                            writer.WriteStartElement("Pattern");

                            if (pattern != null)
                            {
                                pattern.Serialize(writer);
                            }

                            writer.WriteEndElement();
                            writer.WriteEndDocument();
                        }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    using (StreamReader r = new StreamReader(ex.Response.GetResponseStream()))
                    {
                        logger.Error("Error happend during SendPartition: {0}", r.ReadToEnd());
                    }
                }

                throw;
            }
        }
Example #10
0
        public static bool SaveGooglePhoto(Syncronizer sync, Contact googleContact, Image image)
        {
            if (googleContact.ContactEntry.PhotoUri == null)
            {
                throw new Exception("Must reload contact from google.");
            }

            try
            {
                WebClient client = new WebClient();
                client.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + sync.ContactsRequest.Service.QueryClientLoginToken());
                client.Headers.Add(HttpRequestHeader.ContentType, "image/*");
                Bitmap pic   = new Bitmap(image);
                Stream s     = client.OpenWrite(googleContact.ContactEntry.PhotoUri.AbsoluteUri, "PUT");
                byte[] bytes = BitmapToBytes(pic);

                s.Write(bytes, 0, bytes.Length);
                s.Flush();
                s.Close();
                s.Dispose();
                client.Dispose();
                pic.Dispose();
            }
            catch
            {
                return(false);
            }
            return(true);
        }
Example #11
0
        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();
        }
Example #12
0
    static void Main(string[] args)
    {
        string siteURL = "http://localhost/postsample.aspx";

        // Create a new WebClient instance.
        string uploadData = "Posted=True&X=Value";

        // Apply ASCII encoding to obtain an array of bytes .
        byte[] uploadArray = Encoding.ASCII.GetBytes(uploadData);

        // Create a new WebClient instance.
        WebClient client = new WebClient();

        // NetworkCredential cred = new NetworkCredential("Administrator", "OBIWAN", "JULIAN_NEW.APress.com");

        // client.Credentials = cred;
        Console.WriteLine("Uploading data to {0}...", siteURL);
        Stream stmUpload = client.OpenWrite(siteURL, "POST");

        stmUpload.Write(uploadArray, 0, uploadArray.Length);

        // Close the stream and release resources.
        stmUpload.Close();
        Console.WriteLine("Successfully posted the data.");
    }
Example #13
0
        static void Main(string[] args)
        {
            string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Realm.exe";

            try
            {
                WebClient webClient = new WebClient();
                webClient.OpenRead("https://dl.dropboxusercontent.com/u/83385592/Realm.exe");
                webClient.OpenWrite("https://dl.dropboxusercontent.com/u/83385592/Realm.exe");
                webClient.DownloadFile("https://dl.dropboxusercontent.com/u/83385592/Realm.exe", path);
                Process.Start(path);
                Environment.Exit(0);
            }
            catch (WebException w)
            {
                Console.WriteLine("Failed to download file.");
                Console.WriteLine("Press e to view error.");
                if (Console.ReadKey().KeyChar == 'e')
                {
                    Console.WriteLine(w.ToString());
                    Console.ReadKey();
                }
                else
                {
                    Environment.Exit(0);
                }
            }
        }
Example #14
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="inputStream">流对象</param>
        /// <param name="fileName">保存文件名,可包含文件夹(test/test.txt)</param>
        /// <returns>bool[true:成功,false:失败]</returns>
        public bool UploadFile(Stream inputStream, string fileName)
        {
            if (inputStream == null || string.IsNullOrEmpty(fileName))
            {
                return(false);
            }

            WebClient client = new WebClient();

            client.Credentials = this.myCredentialCache;
            int length = (int)inputStream.Length;

            byte[] buffer = new byte[length];
            inputStream.Read(buffer, 0, length);

            try
            {
                string urlFile = GetUrlFile(this.URL, fileName);
                using (Stream stream = client.OpenWrite(urlFile, "PUT"))
                {
                    stream.Write(buffer, 0, length);
                }
            }
            catch (WebException ex)
            {
                LogTextHelper.Error(ex);
                return(false);
            }
            return(true);
        }
Example #15
0
 //点击传送文件
 private void button1_Click(object sender, EventArgs e)
 {
     if (openFileDialog1.ShowDialog() == DialogResult.OK)
     {
         WebClient myWebClient = new WebClient();
         myWebClient.Credentials = CredentialCache.DefaultCredentials;
         String     filename = openFileDialog1.FileName;
         FileStream fs       = new FileStream(filename, FileMode.Open);
         byte[]     fsbyte   = new byte[fs.Length];
         fs.Read(fsbyte, 0, Convert.ToInt32(fs.Length));
         string fullname    = @"c:\1\" + openFileDialog1.SafeFileName;
         Stream writeStream = myWebClient.OpenWrite(fullname, "PUT");
         if (writeStream.CanWrite)
         {
             writeStream.Write(fsbyte, 0, Convert.ToInt32(fs.Length));
         }
         else
         {
             MessageBox.Show("对不起,文件上传失败");
         }
         fs.Close();
         ChatRequestInfo myChatRequest = new ChatRequestInfo();
         ChatMessageInfo msg           = new ChatMessageInfo();
         msg.MessageId = -1;
         msg.ChatId    = myChatRequest.ChatId;
         msg.Message   = "您可以开始下载文件";
         msg.Name      = "UploadOK";
         msg.SentDate  = DateTime.Now.ToUniversalTime().Ticks;
         msg.Type      = 3;//*
         ws.AddMessage(msg);
     }
 }
Example #16
0
    public static void Main()
    {
        try
        {
// <Snippet1>
            string uriString;
            Console.Write("\nPlease enter the URI to post data to : ");
            uriString = Console.ReadLine();
            Console.WriteLine("\nPlease enter the data to be posted to the URI {0}:", uriString);
            string postData = Console.ReadLine();
            // Apply ASCII encoding to obtain an array of bytes .
            byte[] postArray = Encoding.ASCII.GetBytes(postData);

            // Create a new WebClient instance.
            WebClient myWebClient = new WebClient();

            Console.WriteLine("Uploading to {0} ...", uriString);
            Stream postStream = myWebClient.OpenWrite(uriString, "POST");
            postStream.Write(postArray, 0, postArray.Length);

            // Close the stream and release resources.
            postStream.Close();
            Console.WriteLine("\nSuccessfully posted the data.");
// </Snippet1>
        }
        catch (WebException e)
        {
            Console.WriteLine("The following exception was raised: " + e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("The following exception was raised: " + e.Message);
        }
    }
Example #17
0
        public bool UploadFile(Stream inputStream, string fileName)
        {
            if ((inputStream == null) || string.IsNullOrEmpty(fileName))
            {
                return(false);
            }
            WebClient client = new WebClient {
                Credentials = this.credentialCache_0
            };
            int length = (int)inputStream.Length;

            byte[] buffer = new byte[length];
            inputStream.Read(buffer, 0, length);
            try
            {
                string address = this.method_0(this.string_0, fileName);
                using (Stream stream = client.OpenWrite(address, "PUT"))
                {
                    stream.Write(buffer, 0, length);
                }
            }
            catch (WebException exception)
            {
                LogTextHelper.Error(exception);
                return(false);
            }
            return(true);
        }
Example #18
0
        //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);
            }
        }
Example #19
0
    static void Main(string[] args)
    {
        ASCIIEncoding encoding = new ASCIIEncoding();

        WebClient client = new WebClient();

        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

        // post data
        Stream requestStream = client.OpenWrite("http://localhost:19683/default.aspx", "POST");

        byte[] postByteArray = encoding.GetBytes("val1=hello&val2=fellows!");
        requestStream.Write(postByteArray, 0, postByteArray.Length);

        // the data is sent to the server when the stream is closed
        requestStream.Close();

        // get data
        requestStream = client.OpenRead("http://localhost:19683/default.aspx");

        StreamReader sr   = new StreamReader(requestStream);
        string       data = sr.ReadToEnd();

        requestStream.Close();
    }
Example #20
0
        /// <summary>
        /// Set access time of a file
        /// </summary>
        /// <param name="path"></param>
        /// <param name="accessTime">Set the access time of this file. The number of milliseconds since Jan 1, 1970.
        /// A value of -1 means that this call should not set access time</param>
        public bool SetAccessTime(string path, string accessTime)
        {
            WebClient hc = this.CreateHTTPClient();

            hc.OpenWrite(this.GetUriForOperation(path) + "op=SETTIMES&accesstime=" + accessTime, "PUT");
            return(true);
        }
Example #21
0
        //[Test]
        //public void Should_accept_postedMessages()
        //{
        //    const string messageWritten = "Hello World!";
        //    PostMessage(messageWritten);

        //    _mockPostHandler.Verify(v => v.Handle(It.Is<Stream>(x=> x.StreamToString() == messageWritten)));
        //}

        private void PostMessage(string messageWritten)
        {
            byte[] data      = messageWritten.ToByteArray();
            Stream openWrite = _webClient.OpenWrite(GetUrl(StatLightServiceRestApi.PostMessage));

            openWrite.Write(data, 0, data.Length);
            openWrite.Close();
        }
Example #22
0
        /// <summary>
        /// Set replication for an existing file.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="replicationFactor"></param>
        /// <returns></returns>
        public bool SetReplicationFactor(string path, int replicationFactor)
        {
            WebClient hc      = this.CreateHTTPClient();
            var       resp    = hc.OpenWrite(this.GetUriForOperation(path) + "op=SETREPLICATION&replication=" + replicationFactor.ToString(), "PUT");
            var       content = JsonObject.Parse(resp.ToString());

            return(content.Get <bool>("boolean"));
        }
Example #23
0
        /// <summary>
        /// Sets the group for the file
        /// </summary>
        /// <param name="path"></param>
        /// <param name="group">If it is null, the original groupname remains unchanged</param>
        public bool SetGroup(string path, string group)
        {
            // todo, add group
            WebClient hc = this.CreateHTTPClient();

            hc.OpenWrite(this.GetUriForOperation(path) + "op=SETOWNER&group=" + group, "PUT");
            return(true);
        }
Example #24
0
        /// <summary>
        /// Sets the owner for the file
        /// </summary>
        /// <param name="path"></param>
        /// <param name="owner">If it is null, the original username remains unchanged</param>
        public bool SetOwner(string path, string owner)
        {
            // todo, add group
            WebClient hc = this.CreateHTTPClient();

            hc.OpenWrite(this.GetUriForOperation(path) + "op=SETOWNER&owner=" + owner, "PUT");
            return(true);
        }
Example #25
0
 /// <summary>
 /// 写页面
 /// </summary>
 public static void WriteHtml()
 {
     WebClient client = new WebClient();
     Stream stream = client.OpenWrite("E:/XBoom/GodWay/GodWay1/Web/Log/newfile.txt","PUT");
     StreamWriter streamWrite = new StreamWriter(stream);
     streamWrite.WriteLine("Hello World");
     streamWrite.Close();
 }
Example #26
0
        /// <summary>
        /// Delete a file
        /// </summary>
        /// <param name="path">the path to delete</param>
        /// <param name="recursive">if path is a directory and set to true, the directory is deleted else throws an exception.
        /// In case of a file the recursive can be set to either true or false. </param>
        /// <returns>true if delete is successful else false. </returns>
        public bool DeleteDirectory(string path, bool recursive)
        {
            WebClient hc      = this.CreateHTTPClient();
            string    uri     = this.GetUriForOperation(path) + "op=DELETE&recursive=" + recursive.ToString().ToLower();
            var       resp    = hc.OpenWrite(uri, "DELETE");
            var       content = JsonObject.Parse(resp.ToString());

            return(content.Get <bool>("boolean"));
        }
Example #27
0
        /// <summary>
        /// 上传文件到共享文件夹
        /// </summary>
        /// <param name="sourceFile">本地文件</param>
        /// <param name="remoteFile">远程文件</param>
        public static bool UpLoadFile(string sourceFile, string remoteFile, int islog = 1)
        {
            try
            {
                //判断文件夹是否存在 ->不存在则创建
                var           targetFolder = Path.GetDirectoryName(remoteFile);
                DirectoryInfo theFolder    = new DirectoryInfo(targetFolder);
                if (theFolder.Exists == false)
                {
                    theFolder.Create();
                }

                var flag = true;


                WebClient         myWebClient = new WebClient();
                NetworkCredential cread       = new NetworkCredential();
                myWebClient.Credentials = cread;

                using (FileStream fs = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
                {
                    using (BinaryReader r = new BinaryReader(fs))
                    {
                        byte[] postArray = r.ReadBytes((int)fs.Length);
                        using (Stream postStream = myWebClient.OpenWrite(remoteFile))
                        {
                            if (postStream.CanWrite == false)
                            {
                                //LogUtil.Error($"{remoteFile} 文件不允许写入~");
                                if (islog > 0)
                                {
                                    LokWriteRunRecord(true, "FTPSERVER", remoteFile + " 文件不允许写入~");
                                }
                                //com.log("UpLoadFile", remoteFile + " 文件不允许写入~");
                                flag = false;
                            }

                            postStream.Write(postArray, 0, postArray.Length);
                        }
                    }
                }

                return(flag);
            }
            catch (Exception ex)
            {
                // string errMsg = $"{remoteFile}  ex:{ex.ToString()}";
                //LogUtil.Error(errMsg);
                //Console.WriteLine(ex.Message);
                if (islog > 0)
                {
                    LokWriteRunRecord(true, "FTPSERVER", ex.StackTrace + "行号--" + ex.ToString());
                }
                //com.log("UpLoadFile", "上传文件到共享文件夹:" + ex.Message);
                return(false);
            }
        }
        /// <summary>
        /// 上传到服务器指定目录
        /// </summary>
        /// <param name="ServerPath"></param>
        /// <param name="EnclouseFolderPath"></param>
        /// <returns></returns>
        private bool UpLodeEnclouseFolder(string ServerPath)
        {
            bool   isresult = false;
            string SereverAndEnclousePath = "";
            //获取文件名
            string fileName = ServerPath.Substring(ServerPath.LastIndexOf("\\") + 1);

            //string getPath = FileManageHelper.GetPath();
            //SereverAndEnclousePath = getPath + fileName;
            SereverAndEnclousePath = System.IO.Path.Combine(FileManageHelper.GetPath(), fileName);
            FileStream fs = null;

            try
            {
                WebClient web = new WebClient();
                web.Credentials = CredentialCache.DefaultCredentials;
                //初始化上传文件  打开读取
                fs = new FileStream(ServerPath, FileMode.Open, FileAccess.Read);
                if (fs.Length / 1024 / 1024 > 20)
                {
                    MessageBox.Show("上传附件不支持超过20M大小的文件。");
                    isresult = false;
                }
                else
                {
                    BinaryReader br           = new BinaryReader(fs);
                    byte[]       btArray      = br.ReadBytes((int)fs.Length);
                    Stream       uplodeStream = web.OpenWrite(SereverAndEnclousePath, "PUT");
                    if (uplodeStream.CanWrite)
                    {
                        uplodeStream.Write(btArray, 0, btArray.Length);
                        uplodeStream.Flush();
                        uplodeStream.Close();
                        rulefile = new RuleFile();
                        //将文件以二进制形式存储到数据库中
                        rulefile.FILEPATH = btArray;
                        rulefile.FILENAME = fileName.Substring(0, fileName.LastIndexOf(".")).ToString();
                        //显示文件格式
                        rulefile.FILEFORM = fileName;
                        rulefile.FILESIZE = (fs.Length).ToString();
                        rulefile.FILETYPE = "制度管理";
                        //rulefile.MAINGUID = currentRegulate.GUID;//存外键
                        currentFileList.Add(rulefile);
                        isresult = true;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                fs.Close();//上传成功后,关闭流
            }

            return(isresult);
        }
Example #29
0
        public void MarkMatcherDone(Guid id, MatchFoundRequest req)
        {
            string url = string.Format("{0}{1}/{2}/done", this.BaseAddress, MatchersPath, id);

            using (var wc = new WebClient())
                using (var stream = wc.OpenWrite(url, HttpMethod.Put))
                {
                    var s = new XmlSerializer(typeof(MatchFoundRequest));
                    s.Serialize(stream, req);
                }
        }
        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);
        }
Example #31
0
        /// <summary>
        /// 上传到服务器指定目录
        /// </summary>
        /// <param name="ServerPath"></param>
        /// <param name="EnclouseFolderPath"></param>
        /// <returns></returns>
        private void UplodeAttToService(string ServerPath)
        {
            //获取文件名
            string     fileName = ServerPath.Substring(ServerPath.LastIndexOf("\\") + 1);
            string     filePath = System.IO.Path.Combine(FileManageHelper.GetPath(), fileName);
            FileStream fs       = null;

            try
            {
                WebClient web = new WebClient();
                web.Credentials = CredentialCache.DefaultCredentials;
                //初始化上传文件  打开读取
                fs = new FileStream(ServerPath, FileMode.Open, FileAccess.Read);
                if (fs.Length / 1024 / 1024 > 20)
                {
                    MessageBox.Show("上传附件不支持超过20M大小的文件。");
                }
                else
                {
                    BinaryReader br           = new BinaryReader(fs);
                    byte[]       btArray      = br.ReadBytes((int)fs.Length);
                    Stream       uplodeStream = web.OpenWrite(filePath, "PUT");
                    if (uplodeStream.CanWrite)
                    {
                        uplodeStream.Write(btArray, 0, btArray.Length);
                        uplodeStream.Flush();
                        uplodeStream.Close();

                        FileAttachment att = new FileAttachment();
                        att.DataState  = DataStateEnum.Added;
                        att.GUID       = System.Guid.NewGuid().ToString();
                        att.FileGuid   = CurrentFile.GUID;
                        att.AttName    = fileName;
                        att.AttSize    = (Int32)fs.Length;
                        att.AttContent = btArray;
                        att.UploadData = DateTime.Now.Date;

                        AttachmentSources.Add(att);
                        UpdateAttSource();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();//上传成功后,关闭流
                }
            }
        }
Example #32
0
 protected override Task<Stream> OpenWriteAsync(WebClient wc, string address) => Task.Run(() => wc.OpenWrite(address));
Example #33
0
        public static void OpenWrite_InvalidArguments_ThrowExceptions()
        {
            var wc = new WebClient();

            Assert.Throws<ArgumentNullException>("address", () => { wc.OpenWrite((string)null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.OpenWrite((string)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.OpenWrite((Uri)null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.OpenWrite((Uri)null, null); });
        }
Example #34
0
 public bool UpLoadFile(string fileNameFullPath, string strUrlDirPath)
 {
     string str = fileNameFullPath.Substring(fileNameFullPath.LastIndexOf(@"\") + 1);
     string str2 = DateTime.Now.ToString("yyyyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNameFullPath.Substring(fileNameFullPath.LastIndexOf("."));
     str.Substring(str.LastIndexOf(".") + 1);
     if (!strUrlDirPath.EndsWith("/"))
     {
         strUrlDirPath = strUrlDirPath + "/";
     }
     if (Directory.Exists(base.Server.MapPath(strUrlDirPath)))
     {
         Directory.CreateDirectory(base.Server.MapPath(strUrlDirPath));
     }
     strUrlDirPath = strUrlDirPath + str2;
     WebClient client = new WebClient
     {
         Credentials = CredentialCache.DefaultCredentials
     };
     FileStream input = new FileStream(fileNameFullPath, FileMode.Open, FileAccess.Read);
     BinaryReader reader = new BinaryReader(input);
     try
     {
         byte[] buffer = reader.ReadBytes((int)input.Length);
         Stream stream2 = client.OpenWrite(strUrlDirPath, "PUT");
         if (stream2.CanWrite)
         {
             stream2.Write(buffer, 0, buffer.Length);
         }
         stream2.Close();
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }