/// <summary>
        /// Force load of storage file from telegram.
        /// Carefully, you can loose your unsaved data.
        /// </summary>
        public async Task ForceLoad()
        {
            using (await _saveLock.LockAsync())
            {
                var chat = await _botClient.GetChatAsync(_saveResChatId);

                if (chat.PinnedMessage?.Caption?.Trim() != FileResName)
                {
                    //Can't find storage.
                    File.WriteAllText(_storageFilePath, "{}");
                }
                else
                {
                    var fileId = chat.PinnedMessage.Document.FileId;
                    if (File.Exists(_storageFilePath))
                    {
                        File.Delete(_storageFilePath);
                    }
                    using (var stream = File.OpenWrite(_storageFilePath))
                    {
                        await _botClient.GetInfoAndDownloadFileAsync(fileId, stream);
                    }
                }

                LoadStorageStateFromFile();
            }
        }
        private void TryDeleteUnusedAssemblies(string dllPathFile)
        {
            if (File.Exists(dllPathFile))
            {
                var                    dllPath = File.ReadAllText(dllPathFile);
                DirectoryInfo?         dirInfo = new DirectoryInfo(dllPath).Parent;
                IEnumerable <FileInfo>?files   = dirInfo?.GetFiles().Where(f => f.FullName != dllPath);
                if (files is null)
                {
                    return;
                }

                foreach (FileInfo file in files)
                {
                    try
                    {
                        File.Delete(file.FullName);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // The file is in use, we'll try again next time...
                        // This shouldn't happen anymore.
                    }
                }
            }
        }
示例#3
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="Created"></param>
 /// <param name="destopLinkname"></param>
 public static void CreateDesktopLink(bool Created, string destopLinkname)
 {
     if (Created)
     {
         //先判断是否存在
         if (
             !File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\" +
                          destopLinkname + ".lnk"))
         {
             var shell    = new WshShell();
             var shortcut = (IWshShortcut)shell.CreateShortcut(
                 Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\" + destopLinkname +
                 ".lnk");
             shortcut.TargetPath       = Assembly.GetExecutingAssembly().Location;
             shortcut.WorkingDirectory = Environment.CurrentDirectory;
             shortcut.WindowStyle      = 1;
             //Normal window
             shortcut.Description = destopLinkname;
             //
             shortcut.IconLocation = Environment.SystemDirectory + "\\" + "shell32.dll, 165";
             shortcut.Save();
         }
     }
     else
     {
         //先判断是否存在
         if (
             File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\" +
                         destopLinkname + ".lnk"))
         {
             File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\" +
                         destopLinkname + ".lnk");
         }
     }
 }
示例#4
0
        private static string GetAvatarPath(IMember member)
        {
            var url = "http://www.gravatar.com/avatar/" + member.Email.ToMd5() + "?s=400&d=retro";

            try
            {
                var avatarFileName = "/media/avatar/" + member.Id + ".jpg";
                var path           = HostingEnvironment.MapPath(avatarFileName);

                if (path != null)
                {
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }

                    using (var webClient = new WebClient())
                    {
                        webClient.DownloadFile(url, path);
                    }

                    return(avatarFileName);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error <Signup>("Could not save gravatar locally", ex);
            }

            return(url);
        }
示例#5
0
        public async Task File_is_deleted_after_cancel()
        {
            const int timetoWaitBetweenBlocks    = 100;
            const int timetoWaitBeforeCancelling = 250;

            var source = CreateRandomFile(0x10000);

            var copy = new FileCopy(0x1000);

            copy.ProgressChanged += (o, e) =>
            {
                Console.WriteLine(e.Percent);
                // this makes the copy process wait a bit, so there is time for cancellation
                // do not change to await Task.Delay - this would not cause a wait for the operations.
                Thread.Sleep(timetoWaitBetweenBlocks);
            };

            var destination = Guid.NewGuid().ToString();

            var cancellationTokenSource = new CancellationTokenSource();

            cancellationTokenSource.CancelAfter(timetoWaitBeforeCancelling);

            await copy.CopyAsync(source, destination, cancellationTokenSource.Token);

            F.Exists(destination).Should().BeFalse();
            F.Delete(source);
        }
        private void ClearOnFailingToCompile(string dllPathFile, string modelsHashFile, string projFile)
        {
            _logger.LogDebug("Failed to compile.");

            // the dll file reference still points to the previous dll, which is obsolete
            // now and will be deleted by ASP.NET eventually, so better clear that reference.
            // also touch the proj file to force views to recompile - don't delete as it's
            // useful to have the source around for debugging.
            try
            {
                if (File.Exists(dllPathFile))
                {
                    File.Delete(dllPathFile);
                }

                if (File.Exists(modelsHashFile))
                {
                    File.Delete(modelsHashFile);
                }

                if (File.Exists(projFile))
                {
                    File.SetLastWriteTime(projFile, DateTime.Now);
                }
            }
            catch
            { /* enough */
            }
        }
        private void Load()
        {
            if (_loaded)
            {
                return;
            }

            _loaded = true;

            try
            {
                _settings.Load();
            }
            catch (ConfigurationException ex)
            {
                if (!(ex.InnerException is ConfigurationErrorsException configError) ||
                    string.IsNullOrEmpty(configError.Filename))
                {
                    throw;
                }

                File.Delete(configError.Filename);
                SingleInstanceApplication.ReleaseSingleInstanceLock();
                Process.Start(System.Windows.Application.ResourceAssembly.Location);
                Environment.Exit(0);
            }
        }
示例#8
0
 /// <summary>
 ///     Delete the downloaded image.
 /// </summary>
 public void Dispose()
 {
     if (!string.IsNullOrWhiteSpace(Url))
     {
         File.Delete(Path);
     }
     _client?.Dispose();
 }
示例#9
0
 private void DeleteFile()
 {
     if (!fileDeleted && FileIO.Exists(tempFileName))
     {
         FileIO.Delete(tempFileName);
     }
     fileDeleted = true;
 }
示例#10
0
        private void RestartConfirmed()
        {
            var path = Application.persistentDataPath + "save.json";

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            MainController.Instance.toSave = false;
        }
示例#11
0
 public void Delete()
 {
     if (IsFile)
     {
         SysFile.Delete(FullName);
     }
     else if (IsDirectory)
     {
         SysDirectory.Delete(FullName, true);
     }
 }
示例#12
0
        public void Save()
        {
            if (_IsLoaded)
            {
                DirectoryIO.CreateDirectory(DataSavePath);

                String HostListAsText = JsEncoder.EncoderStream.EncodeTable(UserHostList.ToTable(HostList));
                String ConfigAsText; // This won't be null after the region below

                #region ConfigFileSaving
                {
                    JsEncoder.TableValue ConfigTable = new JsEncoder.TableValue();
                    ConfigTable[new JsEncoder.StringValue("UserName")]    = new JsEncoder.StringValue(UserName);
                    ConfigTable[new JsEncoder.StringValue("WorkingPort")] = new JsEncoder.IntValue(WorkingPort);

                    ConfigAsText = JsEncoder.EncoderStream.EncodeTable(ConfigTable);
                }
                #endregion

                String VersionFileBackupPath  = String.Concat(VersionFilePath, ".bak");
                String ConfigFileBackupPath   = String.Concat(ConfigFilePath, ".bak");
                String HostListFileBackupPath = String.Concat(HostListFilePath, ".bak");

                if (FileIO.Exists(VersionFileBackupPath))
                {
                    FileIO.Delete(VersionFileBackupPath);
                }
                if (FileIO.Exists(ConfigFileBackupPath))
                {
                    FileIO.Delete(ConfigFileBackupPath);
                }
                if (FileIO.Exists(HostListFileBackupPath))
                {
                    FileIO.Delete(HostListFileBackupPath);
                }

                if (FileIO.Exists(VersionFilePath))
                {
                    FileIO.Move(VersionFilePath, VersionFileBackupPath);
                }
                if (FileIO.Exists(ConfigFilePath))
                {
                    FileIO.Move(ConfigFilePath, ConfigFileBackupPath);
                }
                if (FileIO.Exists(HostListFilePath))
                {
                    FileIO.Move(HostListFilePath, HostListFileBackupPath);
                }

                FileIO.WriteAllText(VersionFilePath, NetworkConfig.VersionString, System.Text.Encoding.Unicode);
                FileIO.WriteAllText(ConfigFilePath, ConfigAsText, System.Text.Encoding.Unicode);
                FileIO.WriteAllText(HostListFilePath, HostListAsText, System.Text.Encoding.Unicode);
            }
        }
示例#13
0
        /**
         * Adds a new shortcut for the current program to the start menu, if it doesn't exist yet.
         */
        public static void Install(string appId, Guid handler)
        {
            if (!File.Exists(SHORTCUT_PATH))
            {
                File.Delete(SHORTCUT_PATH);
            }

            // Find the path to the current executable
            var exePath = Process.GetCurrentProcess().MainModule.FileName;

            InstallShortcut(exePath, appId, handler);
        }
示例#14
0
        public static void RemakeDatabase()
        {
            //Удалаяем все файлы из папки data/image
            System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(imagesPath);
            foreach (FileInfo file in info.GetFiles())
            {
                file.Delete();
            }

            //Удаляем JSON-файлы
            File.Delete(imagesFile);
            File.Delete(objectClassesFile);
            File.Delete(sessionsFile);
        }
 public static void Valid(this TvDB_ImageFanart fanart)
 {
     if (!File.Exists(fanart.GetFullImagePath()) || !File.Exists(fanart.GetFullThumbnailPath()))
     {
         //clean leftovers
         if (File.Exists(fanart.GetFullImagePath()))
         {
             File.Delete(fanart.GetFullImagePath());
         }
         if (File.Exists(fanart.GetFullThumbnailPath()))
         {
             File.Delete(fanart.GetFullThumbnailPath());
         }
     }
 }
示例#16
0
 /// <summary>
 /// Opens the necessary files and handles a bunch of exceptions.
 /// </summary>
 /// <param name="bmp">Bitmap representing the input image</param>
 /// <param name="fstream">Output file stream</param>
 static string OpenFiles(out Bitmap bmp, out FStream fstream)
 {
     bmp     = null;
     fstream = null;
     try
     {
         bmp = (Bitmap)Bitmap.FromFile(inPath);
         if (grey)
         {
             bmp = ToGreyscale(bmp);
         }
         if (File.Exists(outPath))
         {
             File.Delete(outPath);
         }
         fstream = File.OpenWrite(outPath);
     }
     catch (OutOfMemoryException)
     {
         return("The file at \"" + inPath + "\" is not a valid BMP, GIF, JPEG, PNG, or TIFF format.");
     }
     catch (UnauthorizedAccessException)
     {
         return("You do not have access to \"" + outPath + "\".");
     }
     catch (System.IO.DirectoryNotFoundException)
     {
         return("The path: \"" + outPath + "\" is invalid. The directory does not exist.");
     }
     catch (System.IO.FileNotFoundException)
     {
         return("The path: \"" + inPath + "\" does not exist.");
     }
     catch (System.IO.PathTooLongException)
     {
         return("The path: \"" + outPath + "\" is too long.");
     }
     catch (Exception e)
     {
         if (e is ArgumentException || e is NotSupportedException)
         {
             return("The path: " + (bmp == null ? "\"" + inPath + "\"" : "\"" + outPath + "\"") +
                    " is invalid.");
         }
         throw;
     }
     return(string.Empty);
 }
示例#17
0
文件: File13.cs 项目: Somnium13/SS13
        public static bool Delete(dynamic a)
        {
            if (!(a is string))
            {
                throw new Exception("File13.Delete: Attempt to delete " + a);
            }

            if (!Exists(a))
            {
                return(false);
            }

            SysFile.Delete(Config.DIR_CONTENT + a);

            return(true);
        }
        /// <summary>
        /// Sets/removes app from autostart (depends from the value of autostart checkbox).
        /// </summary>
        public void SetToAutostart()
        {
            if (_autostartCheckbox.IsChecked == null)
            {
                return;
            }

            if (_autostartCheckbox.IsChecked.Value)
            {
                CreateNewAutostartShortcut();
            }
            else
            {
                File.Delete(_autostartShortcutPath);
            }
        }
        protected void startImport_Click(object sender, EventArgs e)
        {
            PanelUpload.Visible = false;

            if (ProductFile.HasFile)
            {
                string tempFile = Server.MapPath(string.Format("~/App_Data/products{0}.csv", Guid.NewGuid()));

                try
                {
                    int count = 0;
                    ProductFile.PostedFile.SaveAs(tempFile);

                    var lines = File.ReadLines(tempFile).Select(a => a.Split(';'));
                    foreach (var product in lines)
                    {
                        // first row is just headers, we'll by pass it
                        if (count > 0)
                        {
                            ImportProduct(
                                int.Parse(product[0]),
                                product[1],
                                int.Parse(product[2]),
                                int.Parse(product[3]));
                        }
                        count++;
                    }

                    ProductCount.Text = count.ToString();
                    PanelWoot.Visible = true;
                    PanelFail.Visible = false;
                }
                catch (Exception ee)
                {
                    failDetail.Text   = ee.ToString();
                    PanelWoot.Visible = false;
                    PanelFail.Visible = true;
                }
                finally
                {
                    if (File.Exists(tempFile))
                    {
                        File.Delete(tempFile);
                    }
                }
            }
        }
        public static void SpatiaLite2_ProviderTestsInitialize(TestContext testContext)
        {
            //testContext.TestDir
            foreach (string fileName in System.IO.Directory.GetFiles(testContext.TestDir + @"\..\..\SharpMap.Data.Providers\SharpMap.Data.Providers.SpatialLite2\SQLite", "lib*.dll"))
            {
                System.IO.File.Copy(fileName, testContext.TestDir + @"\Out\" + System.IO.Path.GetFileName(fileName));
            }

            //Delete possibly existing database file
            if (DBFile.Exists(@"test.sqlite"))
            {
                DBFile.Delete(@"test.sqlite");
            }

            SridMap.DefaultInstance = new SridMap(new[] { new SridProj4Strategy(0, new GeometryServices().CoordinateSystemFactory) });
            _geometryFactory        = new GeometryServices().DefaultGeometryFactory;
        }
示例#21
0
        public void DeleteImage(int index)
        {
            //Удаляем само изображение
            File.Delete(Images[index].Path);

            //Удаляем пути взгляда этого изображения
            for (int i = 0; i < Images[index].EyePaths.Count; i++)
            {
                DeleteEyePath(index, i);
            }

            //Удаляем запись об изображении
            Images.Remove(Images[index]);

            //записываем изменения в файл
            WriteToJSON();
        }
示例#22
0
        public void IsTrue_InfoLevel_InfoMethod_From_Logger()
        {
            var path        = "\\log-info-test.txt";
            var level       = LogLevel.Info;
            var testMessage = "test message";

            var logger = new Logger(new Writer(), path, level);

            logger.Log(new LoggerOptions(LogLevel.Info, testMessage));

            var fullPath = $"{AppDomain.CurrentDomain.BaseDirectory}{path}";
            var result   = File.ReadAllText(fullPath);

            File.Delete(fullPath);

            Assert.IsTrue(result.StartsWith("[INFO]"));
            Assert.IsTrue(result.EndsWith($":{testMessage}\r\n"));
        }
示例#23
0
 public static bool CanWriteInCurrentDirectory()
 {
     if (canWriteInCurrentDirectory == null)
     {
         string path = P.Combine(D.GetCurrentDirectory(), Guid.NewGuid().ToString());
         try
         {
             using (F.Create(path)) { }
             F.Delete(path);
             canWriteInCurrentDirectory = true;
         }
         catch
         {
             canWriteInCurrentDirectory = false;
         }
     }
     return(canWriteInCurrentDirectory.Value);
 }
        private void RemoveDatabaseFile(Action <Exception> onFail = null)
        {
            var path = TestHelper.CurrentAssemblyDirectory;

            try
            {
                var filePath = string.Concat(path, "\\UmbracoNPocoTests.sdf");
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }
            catch (Exception ex)
            {
                Logger.Error <TestWithDatabaseBase>(ex, "Could not remove the old database file");

                // swallow this exception - that's because a sub class might require further teardown logic
                onFail?.Invoke(ex);
            }
        }
示例#25
0
 public IEnumerable <string> WriteFileLines(string path, IEnumerable <string> text, bool overwrite = true)
 {
     try {
         if (SysFile.Exists(path) && overwrite)
         {
             SysFile.Delete(path);
             SysFile.WriteAllLines(path, text);
             return(new List <string>());
         }
         if (SysFile.Exists(path) && !overwrite)
         {
             return(new List <string>());
         }
         SysFile.WriteAllLines(path, text);
         return(new List <string>());
     }
     catch (Exception) {
         return(new List <string>());
     }
 }
示例#26
0
        private NumDataTable?_Execute(Arr <SimParameter> parameters)
        {
            File.Delete(_pathToOutFile);

            var source = _defaultSource.Map(
                p => parameters.Find(pp => pp.Name == p.Name).IfNone(p)
                );

            var scriptObject = new ScriptObject();

            source.Iter(p => scriptObject.Add(p.Name, p.Value));

            var context = new TemplateContext();

            context.PushGlobal(scriptObject);

            var @in = _templateIn.Render(context);

            WriteAllText(_pathToInFile, @in);

            using var run = Process.Start(_processStartInfo);

            RequireNotNull(run, "Failed to start MCSim process");

            run.WaitForExit();

            if (run.ExitCode != 0)
            {
                var stdOut = run.StandardOutput.ReadToEnd();
                var stdErr = run.StandardError.ReadToEnd();
                return(HandleFailure(run.ExitCode, stdOut, stdErr));
            }

            if (!File.Exists(_pathToOutFile))
            {
                var stdOut = run.StandardOutput.ReadToEnd();
                return(HandleIntegrationFailure(stdOut));
            }

            return(ProcessOutFile());
        }
        private string GenerateModelsCode(IList <TypeModel> typeModels)
        {
            if (!Directory.Exists(_pureLiveDirectory.Value))
            {
                Directory.CreateDirectory(_pureLiveDirectory.Value);
            }

            foreach (var file in Directory.GetFiles(_pureLiveDirectory.Value, "*.generated.cs"))
            {
                File.Delete(file);
            }

            var builder = new TextBuilder(_config, typeModels);

            var codeBuilder = new StringBuilder();

            builder.Generate(codeBuilder, builder.GetModelsToGenerate());
            var code = codeBuilder.ToString();

            return(code);
        }
        /// <summary>
        /// Called once the gif is created.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Gif_Created(object sender, EventArgs e)
        {
            string palettePath = this.PalettePath;

            if (File.Exists(palettePath))
            {
                File.Delete(palettePath);
            }

            Dispatcher.BeginInvoke(new Action(delegate {
                this.ProgressBar.IsIndeterminate = false;
                this.Button_Convert.IsEnabled    = true;

                Settings.Default.Fps       = this.Fps;
                Settings.Default.StartTime = this.StartTime;
                Settings.Default.Duration  = this.Duration;
                Settings.Default.Input     = this.Input;
                Settings.Default.Output    = this.Output;

                Settings.Default.Save();
            }), System.Windows.Threading.DispatcherPriority.ApplicationIdle, null);
        }
示例#29
0
        public void Dispose()
        {
            if (!_disposed)
            {
                if (_downloads != null)
                {
                    foreach (string tempFileName in _downloads.Values)
                    {
                        try
                        {
                            File.Delete(tempFileName);
                        }
                        catch
                        {
                            // Suppress exceptions.
                        }
                    }
                }

                _disposed = true;
            }
        }
示例#30
0
        protected override void OnFileChanged()
        {
            Stream inputStream;

            DisposeGraph();
            DeleteFile();
            if (File != null)
            {
                using (inputStream = File.Open())
                {
                    try
                    {
                        byte[] buffer;
                        int    length;

                        checked { length = (int)inputStream.Length; }
                        buffer = new byte[length];
                        if (inputStream.Read(buffer, 0, length) != length)
                        {
                            throw new InvalidOperationException();
                        }
                        CreateFile(buffer);
                        CreateGraph();
                        UpdateInterface();
                        Play();
                    }
                    catch
                    {
                        if (FileIO.Exists(tempFileName))
                        {
                            FileIO.Delete(tempFileName);
                        }
                        UpdateInterface();
                        DisposeGraph();
                        throw;
                    }
                }
            }
        }