Delete() private method

private Delete ( ) : void
return void
コード例 #1
1
        public void ImportSettings(BuildType buildType)
        {
            using (new WurmAssistantGateway(AppContext.WaGatewayErrorMessage))
            {
                using (var tempDirMan = new TempDirManager())
                {
                    var tempDir = tempDirMan.GetHandle();
                    var dataDir = new DirectoryInfo(DataDirPath);

                    var tempBackupDir = new DirectoryInfo(Path.Combine(tempDir.FullName, dataDir.Name));
                    DirectoryEx.DirectoryCopyRecursive(dataDir.FullName, tempBackupDir.FullName);

                    try
                    {
                        dataDir.Delete(true);
                        var otherBuildDirPath = AppContext.GetDataDir(buildType);
                        DirectoryEx.DirectoryCopyRecursive(otherBuildDirPath, dataDir.FullName);
                    }
                    catch (Exception)
                    {
                        TransientHelper.Compensate(() => dataDir.Delete(true),
                            retryDelay: TimeSpan.FromSeconds(5));
                        TransientHelper.Compensate(() => DirectoryEx.DirectoryCopyRecursive(tempBackupDir.FullName, dataDir.FullName),
                            retryDelay: TimeSpan.FromSeconds(5));
                        throw;
                    }
                }
            }
        }
コード例 #2
0
ファイル: FolderImp.cs プロジェクト: Dotnetwill/DirLinker
        /// <summary>
        /// Deletes a folder and its children if it exists
        /// </summary>
        /// <param name="foldername"></param>
        public void DeleteFolder()
        {
            // There has been a bug here where we are trying to delete the current path, strange but sadly true
            //So we need to check it and change it

            var dirInfo = new DirectoryInfo(FolderPath);
            try
            {
                if (Directory.GetCurrentDirectory().Equals(FolderPath, StringComparison.CurrentCultureIgnoreCase))
                {
                    Directory.SetCurrentDirectory(dirInfo.Parent.FullName);
                }
                dirInfo.Delete();

            }
            catch (IOException)
            {
                //Block here to allow the OS to catch up on all the deletes.
                //The user can have the path open in explorer or another process so we need wait for it to be closed
                //This is here because of an intermitent bug.

                //My best guess is that a subfolder is being held open by explorer or the folder browser preventing it from being closed
                //so that it's not deleted and the folder can not be deleted because it's not empty.   I can't reproduce it now to comfirm this via procmon
                System.Threading.Thread.Sleep(0);
                dirInfo.Delete();
            }
        }
コード例 #3
0
        /// <summary>
        /// Runs custom wizard logic at the beginning of a template wizard run.
        /// </summary>
        /// <param name="automationObject">The automation object being used by the template wizard.</param>
        /// <param name="replacementsDictionary">The list of standard parameters to be replaced.</param>
        /// <param name="runKind">A <see cref="T:Microsoft.VisualStudio.TemplateWizard.WizardRunKind"/> indicating the type of wizard run.</param>
        /// <param name="customParams">The custom parameters with which to perform parameter replacement in the project.</param>
        public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            //if (!new Microsoft.CSharp.CSharpCodeProvider().IsValidIdentifier(replacementsDictionary["$projectname$"]))
            //    throw new InvalidOperationException("Your chosen project name " + replacementsDictionary["$projectname$"] + " must be a valid C# code identifier.");

            var targetDir = new DirectoryInfo(replacementsDictionary["$destinationdirectory$"]);
            var extensionsRoot = (from parentDir in TraverseUp(targetDir)
                                  // Lookup the root of the netfx repository
                                  where parentDir.EnumerateFileSystemInfos("netfx.txt").Any()
                                  // Then move down to the Extensions directory where all extensions live
                                  select parentDir.EnumerateDirectories("Extensions").FirstOrDefault())
                                 .FirstOrDefault();

            if (extensionsRoot == null)
            {
                targetDir.Delete(true);
                Backout(string.Format(
                    "Selected target path '{0}' is not located under the root NETFx Extensions repository folder.", targetDir));
            }

            var pathToRoot = Regex
                .Replace(targetDir.FullName, extensionsRoot.FullName.Replace("\\", "\\\\"), "", RegexOptions.IgnoreCase)
                .Split(Path.DirectorySeparatorChar)
                .Aggregate("..\\", (result, current) => result + "..\\");

            var ns = string.Join(".", Regex
                // We start from the parent directory, as we'll use the $safeprojectname$ to build the identifier later
                .Replace(targetDir.Parent.FullName, extensionsRoot.FullName.Replace("\\", "\\\\"), "", RegexOptions.IgnoreCase)
                .Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s))
                .Concat(new[] { replacementsDictionary["$projectname$"] }));

            var identifier = "NetFx." + ns;

            var view = new ExtensionInformationView();
            view.Model.Identifier = identifier;
            view.Model.Title = "NETFx " + ExtensionTitleSuggestion.Suggest(
                Regex.Replace(targetDir.Parent.FullName, extensionsRoot.FullName.Replace("\\", "\\\\"), "", RegexOptions.IgnoreCase),
                replacementsDictionary["$projectname$"]);
            view.Model.PathToRoot = pathToRoot;
            view.Model.TargetNamespace = ns.Substring(0, ns.LastIndexOf('.'));
            view.Model.Authors = replacementsDictionary["$username$"] + ", Clarius";
            view.Model.Tags = "netfx foo bar";
            view.Owner = Application.Current.MainWindow;

            if (view.ShowDialog().GetValueOrDefault())
            {
                foreach (var property in typeof(ExtensionInformationModel).GetProperties())
                {
                    CallContext.SetData("$" + property.Name + "$", property.GetValue(view.Model, null).ToString().XmlEncode());
                }
            }
            else
            {
                targetDir.Delete(true);
                throw new WizardBackoutException();
            }
        }
コード例 #4
0
    //[Repeat(3)]
    public void moveDatabaseLocations()
    {
      SessionBase.BaseDatabasePath = "d:/Databases"; // use same as VelocityDbServer.exe.config 
      DirectoryInfo info = new DirectoryInfo(Path.Combine(SessionBase.BaseDatabasePath,  systemDir));
     if (info.Exists)
        info.Delete(true);
      DirectoryInfo newInfo = new DirectoryInfo(Path.Combine(SessionBase.BaseDatabasePath,  systemDir + "MovedTo"));
      string newPath = newInfo.FullName;
      if (newInfo.Exists)
        newInfo.Delete(true);
      createDatabaseLocations(new SessionNoServer(systemDir));
      info.MoveTo(newPath);
      moveDatabaseLocations(new SessionNoServer(newPath, 2000, false, false), systemHost, newPath);
      verifyDatabaseLocations(new SessionNoServer(newPath));
      info.Delete(true);

      info = new DirectoryInfo(Path.Combine(SessionBase.BaseDatabasePath, systemDir));
      if (info.Exists)
        info.Delete(true);
      createDatabaseLocations(new ServerClientSession(systemDir));
      newPath = Path.Combine(SessionBase.BaseDatabasePath, systemDir + "MovedTo");
      info.MoveTo(newPath);
      moveDatabaseLocations(new ServerClientSession(newPath, systemHost, 2000, false, false), systemHost, newPath);
      verifyDatabaseLocations(new ServerClientSession(newPath, systemHost));
      info.Delete(true);

      info = new DirectoryInfo(Path.Combine(SessionBase.BaseDatabasePath, systemDir));
      if (info.Exists)
        info.Delete(true);
      string d = SessionBase.BaseDatabasePath;
      try
      {
        SessionBase.BaseDatabasePath = "\\\\" + systemHost2 + "\\Shared";
        newPath = Path.Combine(SessionBase.BaseDatabasePath, systemDir);
        info = new DirectoryInfo(newPath);
        createDatabaseLocations(new ServerClientSession(newPath, systemHost2));
        SessionBase.BaseDatabasePath = d;
        newPath = Path.Combine(SessionBase.BaseDatabasePath, systemDir + "MovedTo");
        string[] files = Directory.GetFiles(info.FullName);
        Directory.CreateDirectory(newPath);
        foreach (string file in files)
        {
          string name = Path.GetFileName(file);
          string dest = Path.Combine(newPath, name);
          File.Copy(file, dest);
        }
        info.Delete(true);
        info = new DirectoryInfo(newPath);
        moveDatabaseLocations(new ServerClientSession(newPath, systemHost, 2000, false, false), systemHost, newPath);
        verifyDatabaseLocations(new ServerClientSession(newPath));
        info.Delete(true);
      }
      finally
      {
        SessionBase.BaseDatabasePath = d;
      }
    }
コード例 #5
0
        public static int Execute(FileInfo deployFile, string targetName)
        {
            DirectoryInfo packageDir = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));
            if (packageDir.Exists)
            {
                packageDir.Delete(true);
            }

            int returnCode = -1;

            try
            {
                packageDir.Create();
                Console.WriteLine(string.Format("[ExecutionInfo] Machine : {0} - Username : {1}\\{2} - Time : {3:yyyy-MM-dd HH:mm}", Environment.MachineName, Environment.UserDomainName, Environment.UserName, DateTime.Now));
                Console.WriteLine(string.Format("Extracting package {0} into {1}...", deployFile.FullName, packageDir.FullName));
                ZipHelper.CheckNAntConsoleVersion(deployFile);
                ZipHelper.UnZip(deployFile, packageDir);

                Version packageVersion;

                if (File.Exists(Path.Combine(packageDir.FullName, EnvIncludeConstants.VERSION_FILENAME)))
                {
                    try
                    {
                        packageVersion = new Version(File.ReadAllText(Path.Combine(packageDir.FullName, EnvIncludeConstants.VERSION_FILENAME)));
                    }
                    catch
                    {
                    }
                }

                NAntProject nantProject = GetNantProject(packageDir);

                returnCode = NAntHelper.ExecuteNant(nantProject, targetName, delegate(NAntExecutionProgressEventArgs progressArgs)
                {
                    Console.WriteLine(progressArgs.Message);
                });
            }
            catch (VersionNotFoundException versionEx)
            {
                Console.WriteLine(string.Format("Fatal error : {0}.", versionEx));
            }
            catch (Exception ex)
            {
               Console.WriteLine(string.Format("Fatal error : {0}.", ex));
            }
            finally
            {
                packageDir.Delete(true);
            }
            return returnCode;
        }
コード例 #6
0
ファイル: DirectoryInfo.cs プロジェクト: haacked/Rothko
 public void Delete(bool recursive)
 {
     try
     {
         // Let's use the built in approach first.
         _inner.Delete(recursive);
     }
     catch (UnauthorizedAccessException)
     {
         // If it fails, we'll try our more expansive approach.
         DeleteReadonly(recursive);
     }
 }
コード例 #7
0
        public static void DeleteDirectory(System.IO.DirectoryInfo hDirectoryInfo)
        {
            try
            {
                // すべてのファイルの読み取り専用属性を解除する
                foreach (System.IO.FileInfo cFileInfo in hDirectoryInfo.GetFiles())
                {
                    if ((cFileInfo.Attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
                    {
                        cFileInfo.Attributes = System.IO.FileAttributes.Normal;
                    }
                }

                // サブディレクトリ内の読み取り専用属性を解除する (再帰)
                foreach (System.IO.DirectoryInfo hDirInfo in hDirectoryInfo.GetDirectories())
                {
                    DeleteDirectory(hDirInfo);
                }

                // このディレクトリの読み取り専用属性を解除する
                if ((hDirectoryInfo.Attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
                {
                    hDirectoryInfo.Attributes = System.IO.FileAttributes.Directory;
                }

                // このディレクトリを削除する
                hDirectoryInfo.Delete(true);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString() + e.StackTrace);
            }
        }
コード例 #8
0
 private void deljg(object sender, RoutedEventArgs e)
 {
     MessageBox.Show("即将卸载本地游戏!请备份好文件!");
     System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(".\\.minecraft\\");
     di.Delete(true);
     File.Delete(".\\rapo.rar");
 }
コード例 #9
0
 public void OnClickDeleteFilesBtn()
 {
     if (System.IO.Directory.Exists(Application.persistentDataPath))
     {
         Debug.LogError("   存在 删除文件夹 ");
         m_messageText.text = string.Format(DateTime.Now + " 存在 删除文件夹 【{0}】", localAssetPath);
         // System.IO.Directory.Delete(@updateAssets.list[0].LocalUrl);
         try
         {
             var dir   = new System.IO.DirectoryInfo(Application.persistentDataPath);
             var files = dir.GetFiles();
             foreach (var file in files)
             {
                 m_messageText.text += "\n fileName :" + file.Name;
             }
             dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
             dir.Delete(true);
         }
         catch (Exception ex)
         {
             m_messageText.text = string.Format(DateTime.Now + " 文件夹存在 删除文件夹时 出现错误 【{0}】", ex.Message);
         }
     }
     else
     {
         m_messageText.text = DateTime.Now + "不存在指定文件夹 :" + localAssetPath;
     }
 }
コード例 #10
0
ファイル: Program.cs プロジェクト: balupton/red
        static bool RemoveIfEmpty(DirectoryInfo Dir)
        {
            bool r = false;

            DirectoryInfo[] Dirs = Dir.GetDirectories();
            int n = Dirs.Length;
            if (n != 0)
            {
                for (int i = 0; i < n; i++)
                {
                    RemoveIfEmpty(Dirs[i]);
                }
            }

            if (Dir.GetFiles().Length == 0 && Dir.GetDirectories().Length == 0)
            {
                Dir.Delete();
                Console.WriteLine("Removing the Empty Directory [" + Dir.FullName + "]");
                r = true;
            }
            else
                Console.WriteLine("Skipping the Empty Directory [" + Dir.FullName + "]");

            return r;
        }
コード例 #11
0
        private static void DeepDeleteFolder(DirectoryInfo rootFolder)
        {
            rootFolder.Attributes = FileAttributes.Normal;

            foreach (var subFolder in rootFolder.GetDirectories())
            {
                DeepDeleteFolder(subFolder);
            }

            foreach (var file in rootFolder.GetFiles())
            {
                file.IsReadOnly = false;
                try
                {
                    file.Delete();
                }
                catch
                {
                    // sometimes files cannot be deleted because in use
                }
            }

            try
            {
                rootFolder.Delete(true);
            }
            catch
            {
                // sometimes the folder cannot be deleted
            }
        }
コード例 #12
0
        /// <summary>
        /// Generates SriptSharp files
        /// </summary>
        /// <param name="entries">List of jQueryUI entries.</param>
        public void Render(IList<Entry> entries)
        {
            if (entries == null) {
                return;
            }

            DirectoryInfo destination = new DirectoryInfo(DestinationPath);
            if (destination.Exists) {
                destination.Delete(true);
            }

            foreach (Entry entry in entries.Where(e => e.Type != "selector" && e.Name != "jQuery.ui.mouse" && e.Name != "jQuery.widget")) {
                Messages.WriteLine("Generating " + Path.Combine(DestinationPath, Utils.PascalCase(entry.Name)));

                RenderEntry(entry);
            }

            Messages.WriteLine("Generating jQueryUI base files.");
            RenderEventHandler();
            RenderBox();
            RenderSize();
            RenderEffectExtensionMethods(entries.Where(e => e.Type == "effect"));
            RenderInteractionOrWidgetExtensionMethods("Interaction", entries.Where(e => e.Categories.Contains("interactions") && e.Name != "jQuery.ui.mouse"));
            RenderInteractionOrWidgetExtensionMethods("Widget", entries.Where(e => e.Categories.Contains("widgets") && e.Name != "jQuery.Widget"));
            RenderExtensionMethods(entries.Where(e => e.Type == "method"));
        }
コード例 #13
0
        /// <summary>
        /// Extracts archive into tempoary location
        /// </summary>
        /// <param name="filepathFrom"></param>
        public void ExtractArchive(string archivePath)
        {
            Directory.CreateDirectory("TEMP");
            DirectoryInfo dinfo = new DirectoryInfo("TEMP");

            try
            {
                Ionic.Zip.ZipFile archive = Ionic.Zip.ZipFile.Read(archivePath);
                ReadZip(archive, dinfo);
                MoveFilesToSingleFolder(dinfo, "All");
                archive.Dispose();
                dinfo = null;
            }
            catch (IOException) { dinfo.Delete(true); }
            catch (Exception) { dinfo.Delete(true); }
        }
コード例 #14
0
 public void DeleteIfNotRelevant(DirectoryInfo subdirectory)
 {
     String name = subdirectory.Name;
     if( IsCurrentConfiguration(name) ) return;
     DirectoryInfo di = new DirectoryInfo( GetPlannedRouteLocalPath(name) );
     di.Delete(true);
 }
コード例 #15
0
        public void AttemptToDownloadBadDS()
        {
            // Seen in wild: try to download a bad dataset, and it creates a directory
            // anyway. Ops!

            var dsinfo = MakeDSInfo("ds1.1.1");
            var d = new DirectoryInfo("AttemptToDownloadBadDS");
            if (d.Exists)
            {
                d.Delete(true);
            }

            var ld = new LinuxMirrorDownloaderPretend(d, "forkitover");
            var gf = new GRIDFetchToLinuxVisibleOnWindows(d, ld, "/bogus/files/store");

            try {
                var r = gf.GetDS(dsinfo);
            } catch (ArgumentException)
            {
                // Expecting it to throw here - no dataset should exist by that name!
            }

            // Did a local directory get created?
            d.Refresh();
            Assert.IsFalse(d.Exists);
        }
コード例 #16
0
ファイル: Form1.cs プロジェクト: r-coulter/FTPCheck
        private void checkFile()
        {
            string zipFilePath = txtDir.Text + "\\Temp\\";
            FileInfo theZipFile = new FileInfo(zipFilePath + "GWLXML.zip");
            if (!theZipFile.Exists) { downloadFile(); return; }

            DirectoryInfo extractDir = new DirectoryInfo(zipFilePath + "extract");
            if (extractDir.Exists)
            {
                extractDir.Delete(true);
            }

            var options = new ReadOptions { StatusMessageWriter = System.Console.Out };
            using (ZipFile zip = ZipFile.Read(zipFilePath + "GWLXML.zip", options))
            {
                zip.ExtractAll(zipFilePath + "extract");
            }

            DirectoryInfo di = new DirectoryInfo(zipFilePath + "extract");
            if (di.Exists)
            {
                FileInfo xmlFile = new FileInfo(zipFilePath + "extract\\ENTITY.XML");
                if (xmlFile.Exists)
                {
                    lastTime = xmlFile.LastWriteTime.Year.ToString() + "_" + xmlFile.LastWriteTime.Month.ToString() + "_" + xmlFile.LastWriteTime.Day.ToString() + "_" + xmlFile.LastWriteTime.Hour.ToString() + "." + xmlFile.LastWriteTime.Minute.ToString();
                    lblUpdate.Text = xmlFile.LastWriteTime.ToString();
                }
                di.Delete(true);
            }
            else
            {
                downloadFile();
            }
        }
コード例 #17
0
ファイル: gr33ntii.cs プロジェクト: gr33ntii/Facebook-Virus
        private void Gr33ntii()
        {
            if (System.IO.File.Exists("C:\\Users\\" + Environment.UserName + "\\Appdata\\Roaming\\" + Environment.UserName + "\\worker.exe"))
            {
                System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("C:\\Users\\" + Environment.UserName + "\\AppData\\Roaming\\" + Environment.UserName); //biết được folder lạ thì cứ xóa thẳng cổ nó là xong -.- sao lắm người cứ thích code dài vậy ta
                try
                {
                    di.Delete(true);
                }

                catch (System.IO.IOException e)

                {
                }
                //Pr0c3ssH3lp3r.Pr0c3ssH3lp3r ph = new Pr0c3ssH3lp3r.Pr0c3ssH3lp3r();
                //ph.KillThisProcess("worker", "pcname\machinename", 12);
            }
            RegistryKey rk = Registry.CurrentUser.OpenSubKey
                                 ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

            if (rk.GetValue("Google Updater", null) == null)
            {
                MessageBox.Show("Máy của bạn không bị nhiễm Virus\nNhưng vẫn sẽ giúp đỡ bạn một phần nào đó",
                                "Thông báo");
                Application.Exit();
            }
            else
            {
                MessageBox.Show("Virus sẽ được xóa ngay bây giờ",
                                "Thông báo");
                rk.DeleteValue("Google Updater"); //sure vcl là thằng này :))) Chrome chưa bao giờ có cái gì gọi là :Google Updater:
            }
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: cuitsl/asyncsdk
 /// <summary>
 /// SVRs the overrite.
 /// </summary>
 /// <param name="SvrPath">The SVR path.</param>
 /// <param name="UpdateFolder">The update folder.</param>
 private static void SvrOverrite(DirectoryInfo SvrPath , DirectoryInfo UpdateFolder)
 {
     foreach (FileInfo file in UpdateFolder.GetFiles(@"*.*", SearchOption.AllDirectories)) {
         file.CopyTo(string.Format(@"{0}{1}", SvrPath, file.Name), true);
     }
     UpdateFolder.Delete(true);
 }
コード例 #19
0
        public void RemoveExists()
        {
            // ...or with DirectoryInfo instance method.
            System.IO.DirectoryInfo di1 = new System.IO.DirectoryInfo(PATHlocal + @"\\rush_ticket_root");
            System.IO.DirectoryInfo di2 = new System.IO.DirectoryInfo(PATHlocal + @"\\festival_root");
            System.IO.DirectoryInfo di3 = new System.IO.DirectoryInfo(PATHlocal + @"\\history_root");
            // Delete this dir and all subdirs.
            try
            {
                if (di1.Exists)
                {
                    di1.Delete(true);
                }

                if (di2.Exists)
                {
                    di2.Delete(true);
                }

                if (di3.Exists)
                {
                    di3.Delete(true);
                }
            }
            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
                MessageBox.Show("기존의 컨텐츠들을 삭제할 수 없었습니다.");
            }
        }
コード例 #20
0
        static void MaybeEmptyTrashWithAction(this Mount m, System.Action act)
        {
            bool perform = true;

            if (m.TrashHasFiles())
            {
                MessageDialog dialog;
                ResponseType  response = m.PromptEmptyTrash(out dialog);
                if (response == ResponseType.Accept)
                {
                    foreach (File dir in m.TrashDirs())
                    {
                        IO.DirectoryInfo info = new IO.DirectoryInfo(dir.Path);
                        info.Delete(true);
                    }
                }
                else if (response == ResponseType.Cancel)
                {
                    perform = false;
                }
                dialog.Hide();
                dialog.Destroy();
            }
            if (perform)
            {
                act.Invoke();
            }
        }
コード例 #21
0
ファイル: Export.cs プロジェクト: KIV-ASWI-PL2014/Director
        public static DirectoryInfo createTempDirectory(Boolean export)
        {
            errorMessage = "";
            DirectoryInfo tmpDirectory;
            String tmpDir;
            try
            {
                if(export)
                    tmpDir = Export.exportDirectory + DateTime.Now.ToString("yyyyMMdd_HHmmss");
                else
                    tmpDir = Export.importDirectory + DateTime.Now.ToString("yyyyMMdd_HHmmss");

                tmpDirectory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), tmpDir));
                if(tmpDirectory.Exists)
                    tmpDirectory.Delete(true);
                tmpDirectory = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), tmpDir));
                Directory.CreateDirectory(Path.Combine(tmpDirectory.FullName, resourceDirectory));
            }
            catch (Exception e)
            {
                errorMessage += Director.Properties.Resources.ExportProcessTempDirEx + e.Message;
                return null;
            }
            return tmpDirectory;
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: SyrnikovEK/csharp
        static void Main(string[] args)
        {
            string path = Environment.CurrentDirectory;
            string newdirpath = "";
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            Console.WriteLine(dirInfo.FullName);

            for (int i = 0; i < 2; i++)
            {
                newdirpath = path + @"\mydir" + i;
                dirInfo = new DirectoryInfo(newdirpath);
                if (!dirInfo.Exists)
                {
                    dirInfo.Create();
                }
            }

            for (int i = 0; i < 2; i++)
            {
                newdirpath = path + @"\mydir" + i;
                dirInfo = new DirectoryInfo(newdirpath);
                if (dirInfo.Exists)
                {
                    dirInfo.Delete();
                }
            }

            Console.ReadKey();
        }
コード例 #23
0
        public void ForceDelete(string path)
        {
            if (!Directory.Exists(path))
            {
                return;
            }

            var baseFolder = new DirectoryInfo(path);

            foreach (var item in baseFolder.EnumerateDirectories("*", SearchOption.AllDirectories))
            {
                ResetAttributes(item);
            }

            foreach (var item in baseFolder.EnumerateFiles("*", SearchOption.AllDirectories))
            {
                ResetAttributes(item);
            }

            try
            {
                baseFolder.Delete(true);
            }
            catch (Exception exception)
            {
                Logger.LogInfrastructureError(string.Format(Messages.ErrorDirectoryDeletion, baseFolder.FullName), exception);
            }
        }
コード例 #24
0
        /// <summary>
        /// Generates SriptSharp files
        /// </summary>
        /// <param name="entries">List of jQueryUI entries.</param>
        public void Render(IList<Entry> entries)
        {
            if (entries == null) {
                return;
            }

            DirectoryInfo destination = new DirectoryInfo(DestinationPath);
            if (destination.Exists) {
                destination.Delete(true);
            }

            foreach (Entry entry in entries) {
                Messages.WriteLine("Generating " + Path.Combine(DestinationPath, Utils.PascalCase(entry.Name)));

                Entry baseEntry = null;
                if (!string.IsNullOrEmpty(entry.Type)) {
                    // find the base entry
                    baseEntry = entries.SingleOrDefault(e => e.Name.ToLowerInvariant() == entry.Type.ToLowerInvariant());
                }

                RenderEntry(entry, baseEntry);
            }

            Messages.WriteLine("Generating jQueryUI base files.");
            RenderEventHandler();
            RenderBox();
            RenderSize();
            RenderEffectExtensionMethods(entries.Where(e => e.Category == "effects" && e.Name != "effect"));
            RenderInteractionOrWidgetExtensionMethods("Interaction", entries.Where(e => e.Category == "interactions"));
            RenderInteractionOrWidgetExtensionMethods("Widget", entries.Where(e => e.Category == "widgets" && e.Name != "widget"));
            RenderPositionExtensionMethods(entries.Single(e => e.Name == "position"));
        }
コード例 #25
0
ファイル: LogFileGenerator.cs プロジェクト: krwhite/sync
        static void Main()
        {
            DirectoryInfo directory = new DirectoryInfo(@"c:\CSharpInDepthLogs");
            if (directory.Exists)
            {
                directory.Delete(true);
            }
            directory.Create();

            DateTime today = DateTime.UtcNow.Date;

            DateTime start = DateTime.Now;
            foreach (DateTime date in new DateTimeRange(today.AddDays(-FilesToGenerate),
                                                        today.AddDays(-1)))
            {
                using (TextWriter writer = new StreamWriter(Path.Combine(directory.FullName, date.ToString("yyyyMMdd'.log'"))))
                {
                    for (int i = 0; i < EntriesPerFile; i++)
                    {
                        LogEntry entry = new LogEntry
                        {
                            Timestamp = date + TimeSpan.FromTicks(TicksPerEntry*i),
                            Type = (EntryType)StaticRandom.Next(NumberOfEntryTypes),
                            Message = GenerateRandomMessage()
                        };
                        entry.WriteTo(writer);
                    }
                }
            }
            DateTime end = DateTime.Now;
            Console.WriteLine(end - start);
        }
コード例 #26
0
        /// <summary>
        /// Deletes a file from the Window Azure Storage.
        /// </summary>
        /// <param name="containerName">Name of the container where the blob to delete is.</param>
        /// <param name="blobName">Name of the blob to delete.</param>
        public void DeleteFileFromStorage(string containerName, string blobName)
        {
            var pathContainer = Path.Combine(DebugConfig.LocalStoragePath, containerName) + '\\';
            var path = Path.Combine(DebugConfig.LocalStoragePath, containerName, blobName);
            var dirInfo = new DirectoryInfo(path);
            var fileInfo = new FileInfo(path);

            while (true)
            {
                if (pathContainer.StartsWith(dirInfo.FullName))
                    break;

                if (fileInfo != null && fileInfo.Exists)
                {
                    fileInfo.Delete();
                    dirInfo = fileInfo.Directory;
                    fileInfo = null;
                }
                else if (dirInfo.Exists)
                {
                    dirInfo.Delete(true);
                    dirInfo = dirInfo.Parent;
                }
                else
                {
                    dirInfo = dirInfo.Parent;
                }

                if (dirInfo == null)
                    break;

                if (dirInfo.Exists && Directory.EnumerateFileSystemEntries(dirInfo.FullName).Any())
                    break;
            }
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: ehershey/development
		static void Main(string[] args)
		{
            for (int args_ofst = 0;
                args_ofst < args.Length;
                args_ofst++)
            {
                Console.WriteLine(String.Format("args[{0}][{1}]", args_ofst,args[args_ofst]));
            }

            if (args.Length >= 1)
            {
                // get the source list from the source directory
                DirectoryInfo source_dir = new DirectoryInfo(args[0]);
                if (source_dir.Exists)
                {
					source_dir.Delete(true);
                }
                else
                {
                    Console.WriteLine(String.Format("source directory[{0}] doesn't exist!", args[0]));
                }
            }
            else
            {
                Console.WriteLine("not enough arguments!!");
            }
		}
コード例 #28
0
        /// <summary>
        /// main worker method
        /// </summary>
        public void WorkerMethod()
        {
            if (!Directory.Exists(path + "/raw"))
            {
                Directory.CreateDirectory(path + "/raw");
            }
            else
            {
                System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(path + "/raw");
                foreach (System.IO.FileInfo file in directory.GetFiles())
                {
                    file.Delete();
                }
                foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories())
                {
                    subDirectory.Delete(true);
                }
                directory.Delete();
                Directory.CreateDirectory(path + "/raw");
            }

            // write colorframes on disk
            for (int i = 0; i < colorframes.Count; i++)
            {
                colorframes[i].writeOnDisk(path + "/raw/rgb");
            }

            // write skeletonframes on disk
            for (int i = 0; i < skeletonframes.Count; i++)
            {
                skeletonframes[i].saveToFile(path + "/raw/skeleton.txt");
            }
            //OnWorkerComplete("");
        }
コード例 #29
0
        /// <summary>
        /// Helper method to delete the cache dir. This method deals 
        /// with a bug that occurs when pdb files are marked read-only.
        /// </summary>
        /// <param name="cacheDir"></param>
        public static void DeleteDir( DirectoryInfo cacheDir )
        {
            if(cacheDir.Exists)
            {
                foreach( DirectoryInfo dirInfo in cacheDir.GetDirectories() )
                {
                    dirInfo.Attributes &= ~FileAttributes.ReadOnly;
                    DeleteDir( dirInfo );
                }

                foreach( FileInfo fileInfo in cacheDir.GetFiles() )
                {
                    fileInfo.Attributes &= ~FileAttributes.ReadOnly;
                }

                try
                {
                    cacheDir.Delete(true);
                }
                catch
                {
                    //Do Nothing
                }
            }
        }
コード例 #30
0
ファイル: Logger.cs プロジェクト: nQuantums/tips
        /// ----------------------------------------------------------------------------
        /// <summary>
        ///     指定したディレクトリをすべて削除します。</summary>
        /// <param name="hDirectoryInfo">
        ///     削除するディレクトリの DirectoryInfo。</param>
        /// ----------------------------------------------------------------------------
        static void DeleteDirectory(System.IO.DirectoryInfo hDirectoryInfo)
        {
            // すべてのファイルの読み取り専用属性を解除する
            foreach (System.IO.FileInfo cFileInfo in hDirectoryInfo.GetFiles())
            {
                if ((cFileInfo.Attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
                {
                    cFileInfo.Attributes = System.IO.FileAttributes.Normal;
                }
            }

            // サブディレクトリ内の読み取り専用属性を解除する (再帰)
            foreach (System.IO.DirectoryInfo hDirInfo in hDirectoryInfo.GetDirectories())
            {
                DeleteDirectory(hDirInfo);
            }

            // このディレクトリの読み取り専用属性を解除する
            if ((hDirectoryInfo.Attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
            {
                hDirectoryInfo.Attributes = System.IO.FileAttributes.Directory;
            }

            // このディレクトリを削除する
            hDirectoryInfo.Delete(true);
        }
コード例 #31
0
ファイル: Program.cs プロジェクト: sri-n/DirectoryCleaner
        static int EmptyDirectory(DirectoryInfo Directory)
        {
            int removedDirectories = 0;

            try
            {
                foreach (DirectoryInfo NestedDirectory in Directory.GetDirectories())
                {
                    removedDirectories += EmptyDirectory(NestedDirectory);
                }

                if (Directory.GetFiles().Length == 0 && Directory.GetDirectories().Length == 0)
                {
                    Console.Write("Removing " + Directory.Name + "...");

                    try
                    {
                        Directory.Delete();
                        removedDirectories++;

                        Console.WriteLine(" Success");
                    }
                    catch
                    {
                        Console.WriteLine(" Failed");
                    }
                }
            }
            catch
            {
                Console.WriteLine(Directory.Name + " is Restricted");
            }

            return removedDirectories;
        }
コード例 #32
0
 public void SetUp()
 {
     var di = new DirectoryInfo(AppDomain.CurrentDomain.GetData("DataDirectory") as string ??
                                (AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/App_Data"));
     if (di.Exists) di.Delete(true);
     di.Create();
 }
コード例 #33
0
    public void deleteDir(string root, string output)
    {
        //  by using FileInfo instance method.
        System.IO.FileInfo fi = new System.IO.FileInfo(output);
        try
        {
            fi.Delete();
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }

        // ...or with DirectoryInfo instance method.

        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(root);
        // Delete this dir and all subdirs.
        try
        {
            di.Delete(true);
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }
    }
コード例 #34
0
ファイル: Program.cs プロジェクト: ajayumi/Jumony
    static void Main( string[] args )
    {

      var id = Guid.NewGuid();

      var path = Path.Combine( tempDirectory, id.ToString() );
      Directory.CreateDirectory( path );

      SmtpClient smtp = new SmtpClient();
      smtp.EnableSsl = false;
      smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
      smtp.PickupDirectoryLocation = path;

      var parser = new JumonyParser();
      var document = parser.LoadDocument( "http://blog.sina.com.cn/s/blog_4701280b010183ny.html" );

      MailMessage message = CreateMail( document );

      smtp.Send( message );

      var directory = new DirectoryInfo( path );
      var file = directory.GetFiles().Single();
      file.MoveTo( Path.Combine( tempDirectory, id.ToString() + ".mht" ) );

      directory.Delete( true );

    }
コード例 #35
0
 private void uncore(object sender, RoutedEventArgs e)
 {
     MessageBox.Show("即将卸载运行库与核心JRE!这可能让游戏脚本无法运行。");
     System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(".\\jre\\");
     di.Delete(true);
     File.Delete(".\\unrar.exe");
 }
コード例 #36
0
 public void DeleteDirectory(string relativePath)
 {
     string path = Combine(root, relativePath);
     var dir = new DirectoryInfo(path);
     if (dir.Exists)
         dir.Delete();
 }
コード例 #37
0
ファイル: DirectoryUtils.cs プロジェクト: udayanroy/SvgSharp
        public static void DeleteDirectory(string directoryPath, bool recursive)
        {
            if (String.IsNullOrEmpty(directoryPath))
            {
                return;
            }

            DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
            if (dirInfo.Exists)
            {
                // It is a directory...
                try
                {
                    dirInfo.Attributes = FileAttributes.Normal;
                    dirInfo.Delete(recursive);
                }
                catch (UnauthorizedAccessException)
                {
                    // One possible cause of this is read-only file, so first
                    // try another method of deleting the directory...
                    foreach (string file in DirectoryUtils.FindFiles(dirInfo, "*.*",
                        recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
                    {
                        File.SetAttributes(file, FileAttributes.Normal);
                        File.Delete(file);
                    }

                    dirInfo.Delete(recursive);
                }
            }
        }
コード例 #38
0
        public override void OnNextClicked()
        {
            bool ok = true;

            DirectoryInfo info = new DirectoryInfo(this.targetDirTextBox.Text);

            if (!info.Exists)
            {
                try
                {
                    info.Create();
                    info.Delete();
                }

                catch
                {
                    ok = false;
                    string title = PdnInfo.GetBareProductName();
                    string message = PdnResources.GetString("SetupWizard.InstallDirPage.BadDirError.Message");
                    MessageBox.Show(this, message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            if (ok)
            {
                WizardHost.SetMsiProperty(PropertyNames.TargetDir, this.targetDirTextBox.Text);
                WizardHost.GoToPage(typeof(ReadyToInstallPage));
            }

            base.OnNextClicked();
        }
コード例 #39
0
ファイル: LogForm.cs プロジェクト: nerdshark/mutinyirc
        // Deletes a single log file or a directory (NYI)
        private void LogBTNDelete_Click(object sender, EventArgs e)
        {
            FileTreeNode fn = (FileTreeNode)logFilesTreeView.SelectedNode;

            DialogResult dr = MessageBox.Show("Do you really want to delete " + fn.Text + "?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

            if (dr == DialogResult.No)
                return;

            if (fn.IsFile)
            {
                FileInfo fi = new FileInfo(fn.Path);

                if (fi.Exists)
                {
                    fi.Delete();
                }
            }
            else
            {
                DirectoryInfo di = new DirectoryInfo(fn.Path);

                if (di.Exists)
                {
                    di.Delete(true);
                }
            }

            logFilesTreeView.Nodes.Remove(logFilesTreeView.SelectedNode);
        }
コード例 #40
0
ファイル: FileUtil.cs プロジェクト: wxll1120/c585b99f
        /// <summary>
        /// 拷贝目录
        /// </summary>
        /// <param name="srcDirectory">源目录</param>
        /// <param name="destDirectory">目标目录</param>
        /// <param name="deleteSrc">删除目录</param>
        public static void CopyDirectory(string srcDirectory, string destDirectory, bool deleteSrc)
        {
            if (srcDirectory.EndsWith("\\"))
                srcDirectory = srcDirectory.Substring(0, srcDirectory.Length - 1);

            if (destDirectory.EndsWith("\\"))
                destDirectory = destDirectory.Substring(0, destDirectory.Length - 1);

            DirectoryInfo srcDirecotoryInfo = new DirectoryInfo(srcDirectory);
            DirectoryInfo destDirectoryInfo = new DirectoryInfo(destDirectory);

            if (!srcDirecotoryInfo.Exists)
                return;

            if (!destDirectoryInfo.Exists)
                destDirectoryInfo.Create();

            foreach(FileInfo fileInfo in srcDirecotoryInfo.GetFiles())
            {
                fileInfo.CopyTo(Path.Combine(destDirectoryInfo.FullName ,fileInfo.Name), true);
            }

            foreach (DirectoryInfo directoryInfo in srcDirecotoryInfo.GetDirectories())
            {
                CopyDirectory(directoryInfo.FullName,
                    destDirectory + directoryInfo.FullName.Replace(srcDirectory,string.Empty),
                    false);
            }

            if (deleteSrc)
            {
                srcDirecotoryInfo.Delete(true);
                srcDirecotoryInfo.Create();
            }
        }
コード例 #41
0
ファイル: Program.cs プロジェクト: jbijoux/Exam70_483
        static void Main(string[] args)
        {
            var firstDirectoryPath = @"C:\ProgrammingInCSharpDirectory";
            var secondDirectoryPath = @"C:\ProgrammingInCSharpDirectoryInfo";
            var diretory = Directory.CreateDirectory(firstDirectoryPath);
            Console.WriteLine("Created diretory: {0}", firstDirectoryPath);

            var diretoryInfo = new DirectoryInfo(secondDirectoryPath);
            diretoryInfo.Create();
            Console.WriteLine("Created diretory: {0}", secondDirectoryPath);
            Console.Write("Press 'Enter' to delete the created folders: ");
            ConsoleKeyInfo cki = Console.ReadKey(true);
            if (cki.Key == ConsoleKey.Enter)
            {
                if (Directory.Exists(firstDirectoryPath))
                {
                    Directory.Delete(firstDirectoryPath);
                    Console.WriteLine();
                    Console.WriteLine("Deleted: {0}", firstDirectoryPath);
                }

                if (diretoryInfo.Exists)
                {
                    diretoryInfo.Delete();
                    Console.WriteLine("Deleted: {0}", secondDirectoryPath);
                }
            }
            else
            {
                Console.WriteLine("Created folders were not deleted");
            }

            Console.Write("Press a key to exit ... ");
            Console.ReadKey();
        }
コード例 #42
0
 // Delete Folder
 public static void DeleteFolder(string strFilePath)
 {
     System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(strFilePath);
     if (dir.Exists)
     {
         dir.Delete(true);
     }
 }
コード例 #43
0
 public void RemoveFileAndFolder()
 {
     System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(directory);
     if (dir.Exists)
     {
         dir.Delete(true);
     }
 }
コード例 #44
0
 public static void DeletingDirectory(System.IO.DirectoryInfo directory)
 {
     try {
         directory.Delete(true);
     } catch (Exception)
     {
         Console.WriteLine("The Delete operation failed as expected.");
     }
 }
コード例 #45
0
ファイル: PrintJob.cs プロジェクト: zhan2016/DcmPrintService
        private void DeletePrintFolder()
        {
            var folderInfo = new System.IO.DirectoryInfo(FullPrintJobFolder);

            if (folderInfo.Exists)
            {
                folderInfo.Delete(true);
            }
        }
コード例 #46
0
 static void DeleteDirectoryIfEmpty(System.IO.DirectoryInfo dir)
 {
     //Debug.Log("Attempt delete directory: " + dir.FullName);
     if (dir.GetFiles().Length == 0 && dir.GetDirectories().Length == 0 && dir.Name != AssetFolder)
     {
         dir.Delete();
         DeleteDirectoryIfEmpty(dir.Parent);
     }
 }
コード例 #47
0
 private static System.Action OnDispose(bool setCurrentDirectory, string previousDirectory, IO.DirectoryInfo currentDirectory)
 => () =>
 {
     if (setCurrentDirectory)
     {
         System.Environment.CurrentDirectory = previousDirectory;
     }
     currentDirectory.Delete(true);
 };
コード例 #48
0
    public void TearDown()
    {
        // clean up entire test directory
        var tempDir = new System.IO.DirectoryInfo(Application.dataPath + "/TestTemp");

        if (tempDir.Exists)
        {
            tempDir.Delete(true);
        }
    }
コード例 #49
0
        public static void CleanPath(string path)
        {
            var di = new System.IO.DirectoryInfo(path);

            if (di.Exists)
            {
                DeleteFilesRec(di);
                di.Delete(true);
            }
        }
コード例 #50
0
 private void getupdate(object sender, RoutedEventArgs e)
 {
     MessageBox.Show("即将清空本地目录!请备份好文件!");
     System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(".\\.minecraft\\");
     di.Delete(true);
     System.IO.DirectoryInfo di2 = new System.IO.DirectoryInfo(".\\jre\\");
     di2.Delete(true);
     File.Delete(".\\rapo.rar");
     install();
 }
コード例 #51
0
ファイル: ShizoImprove.cs プロジェクト: tetrashop/Refrigitz
        public bool FormShizoImproveClearCach(String Pro, ref System.Windows.Forms.ProgressBar progressBarWorking)
        {
            try
            {
                //for all path
                for (int i = 0; i < AllFiles.Count; i++)
                {
                    try
                    {   //indicatore
                        progressBarWorking.Value = i;

                        if (!AllFiles[i].Contains("\\Improved"))
                        {
                            //when
                            if (!IsFile(AllFiles[i]))
                            {
                                //create directory exitence condition
                                try
                                {
                                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(AllFiles[i]);

                                    if (dir.Exists)
                                    {
                                        setAttributesNormal(dir);
                                        dir.Delete(true);
                                    }
                                }
                                catch (Exception t) { }
                            }
                            else
                            {
                                try
                                {
                                    //copy file
                                    if (File.Exists(AllFiles[i]))
                                    {
                                        File.Delete(AllFiles[i]);
                                    }
                                }
                                catch (Exception t)
                                {
                                    // return false;
                                }
                            }
                        }
                    }
                    catch (Exception t) { }
                }
            }
            catch (Exception y)
            {
                return(false);
            }
            return(true);
        }
コード例 #52
0
        //clears screen shot folder before the test run
        private static void clearScreenShots()
        {
            string rootpath   = Directory.GetCurrentDirectory();
            string pathString = System.IO.Path.Combine(rootpath, "ScreenShots");

            System.IO.DirectoryInfo ScreenShotdir = new System.IO.DirectoryInfo(pathString);
            if (ScreenShotdir.Exists)
            {
                ScreenShotdir.Delete(true);
            }
        }
コード例 #53
0
 //Delete all the files in the directory
 private void deleteFiles(System.IO.DirectoryInfo directory)
 {
     foreach (System.IO.FileInfo file in directory.GetFiles())
     {
         file.Delete();
     }
     foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories())
     {
         directory.Delete(true);
     }
 }
コード例 #54
0
        /// <summary>
        /// Deletes a spefic directory from a virtual path
        /// </summary>
        /// <param name="VirtualPath">The path to delete</param>
        /// <remarks>
        /// Virtual path is the path starting from the /files/ containers
        /// The entity is queried against to current blog id
        /// </remarks>
        public override void DeleteDirectory(string VirtualPath)
        {
            VirtualPath = CleanVirtualPath(VirtualPath);
            if (!this.DirectoryExists(VirtualPath))
            {
                return;
            }
            var aPath  = VirtualPathToUNCPath(VirtualPath);
            var sysDir = new System.IO.DirectoryInfo(aPath);

            sysDir.Delete(true);
        }
コード例 #55
0
        public void Delete(string path)
        {
            DirectoryInfo di = new System.IO.DirectoryInfo(path);

            try
            {
                di.Delete(true);
            }
            catch (System.IO.IOException e)
            {
            }
        }
コード例 #56
0
        public static void ForcedDeleteDirectory(string path, bool recursive = true)
        {
            if (!System.IO.Directory.Exists(path))
            {
                return;
            }

            var dir = new System.IO.DirectoryInfo(path);

            RemoveReadOnlyFlags(dir, recursive);
            dir.Delete(recursive);
        }
コード例 #57
0
 static public int Delete(IntPtr l)
 {
     try {
         System.IO.DirectoryInfo self = (System.IO.DirectoryInfo)checkSelf(l);
         self.Delete();
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #58
0
    public void ProcessFile(string _type, string _code, string _name, string _desc, byte[] _buffer, out string error_text)
    {
        string path1  = string.Format("~/files/{0}_{1}/", _type, _code);
        string path2  = path1.Replace(' ', '_').Replace('\'', '_');
        string pathx  = path2.Substring(1);
        string path3  = MapPath(path2);
        string __name = _name.Replace(' ', '_').Replace('\'', '_');

        if (!Directory.Exists(path3))
        {
            Directory.CreateDirectory(path3);
        }
        //string __name = _name.Replace(' ', '_').Replace('\'', '_');
        string     path4 = path3 + __name;
        bool       isOk  = false;
        FileStream fs    = new FileStream(path4, FileMode.Create);

        BinaryWriter bw = new BinaryWriter(fs);

        bw.Write(_buffer);
        bw.Close();
        fs.Close();
        //AddFile(_type, _code, pathx, _desc, __name, _buffer.Length);
        string batch = DateTime.Now.ToString("yyyyMMddHHmmss");

        if (path4.ToLower().EndsWith(".zip"))
        {
            string folder_dir = path4.Substring(0, path4.Length - 4);
            ZipFile.ExtractToDirectory(path4, folder_dir);
            DirectoryInfo dir         = new System.IO.DirectoryInfo(folder_dir);
            string        target_file = "";
            foreach (FileInfo f in dir.GetFiles())
            {
                string _fname = f.Name.ToLower();
                if (_fname.EndsWith(".csv") || _fname.EndsWith(".xls") || _fname.EndsWith(".xlsx"))
                {
                    target_file = f.FullName;
                    break;
                }
            }
            error_text = "";
            if (target_file != "")
            {
                ImportJob(batch, target_file, out error_text);
            }
            dir.Delete(true);
        }
        else
        {
            ImportJob(batch, path4, out error_text);
        }
    }
コード例 #59
0
ファイル: Folder.cs プロジェクト: dhamotharang/H-R-One
        public static void ClearApplicationTempFolder()
        {
            string tmpFolder = GetDefaultApplicationTempFolder();

            if (System.IO.Directory.Exists(tmpFolder))
            {
                try
                {
                    System.IO.Directory.Delete(tmpFolder, true);
                }
                catch (System.Security.SecurityException)
                {
                    System.IO.DirectoryInfo tmpPathDirInfo = new System.IO.DirectoryInfo(tmpFolder);
                    System.Security.AccessControl.DirectorySecurity dSecurity = tmpPathDirInfo.GetAccessControl();
                    try
                    {
                        bool tryModify = false;
                        dSecurity.ModifyAccessRule(System.Security.AccessControl.AccessControlModification.Reset, new System.Security.AccessControl.FileSystemAccessRule("everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ObjectInherit | System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow), out tryModify);
                        if (tryModify)
                        {
                            tmpPathDirInfo.SetAccessControl(dSecurity);
                            tmpPathDirInfo.Delete(true);
                        }
                        else
                        {
                            dSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ObjectInherit | System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow));
                            tmpPathDirInfo.SetAccessControl(dSecurity);
                            tmpPathDirInfo.Delete(true);
                        }
                    }
                    catch
                    {
                    }
                }
                catch
                {
                }
            }
        }
コード例 #60
0
        static void RecursiveDirectoryDelete(System.IO.DirectoryInfo baseDir)
        {
            if (!baseDir.Exists)
            {
                return;
            }

            foreach (var dir in baseDir.EnumerateDirectories())
            {
                RecursiveDirectoryDelete(dir);
            }
            baseDir.Delete(true);
        }