CreateDirectory() public static method

public static CreateDirectory ( string path ) : System.IO.DirectoryInfo
path string
return System.IO.DirectoryInfo
Exemplo n.º 1
0
        public void BaselineTestCreateDirectory()
        {
            var tempPath = Path.Combine(uncDirectory, Pri.LongPath.Path.GetRandomFileName());
            var di       = Directory.CreateDirectory(tempPath);

            try {
                Assert.IsNotNull(di);
                Assert.IsTrue(Directory.Exists(tempPath));
            }
            finally {
                Directory.Delete(tempPath);
            }
        }
Exemplo n.º 2
0
        public DirectoryBackup(string source, string destination)
        {
            this.source      = source;
            this.destination = destination;

            tempPath = Path.GetTempFileName();
            File.Delete(tempPath);
            Directory.CreateDirectory(tempPath);
            if (Directory.Exists(destination) == false)
            {
                Directory.CreateDirectory(destination);
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// Создает новый каталог.
 /// </summary>
 public override void create()
 {
     for (int i = 0; i < dirList.Count; i++)
     {
         try
         {
             string newName = new System.IO.DirectoryInfo(dirList[i]).FullName;
             ClassDir.CreateDirectory(newName.Replace("/" + new System.IO.DirectoryInfo(dirList[i]).Name, "") + System.IO.Path.GetRandomFileName().Replace(".", ""));
             messenger(string.Format("Создан новый обьект с именем {0}. \n", dirList[i]));
         }
         catch (Exception e) { messenger(e.Message); }
     }
 }
Exemplo n.º 4
0
        private static void EnsureIndexWriterCore(bool creatingIndex)
        {
            if (!Directory.Exists(LuceneCommon.IndexOutDoorDirectory))
            {
                Directory.CreateDirectory(LuceneCommon.IndexOutDoorDirectory);
            }

            var analyzer      = new PanGuAnalyzer();
            var directoryInfo = new DirectoryInfo(LuceneCommon.IndexOutDoorDirectory);
            var directory     = new SimpleFSDirectory(directoryInfo);

            _indexWriter = new IndexWriter(directory, analyzer, create: creatingIndex, mfl: IndexWriter.MaxFieldLength.UNLIMITED);
        }
Exemplo n.º 5
0
        private string CreateZipFile()
        {
            _directoryPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            Directory.CreateDirectory(_directoryPath);
            File.WriteAllText(Path.Combine(_directoryPath, "file1.txt"), "data");
            File.WriteAllText(Path.Combine(_directoryPath, "file2.txt"), "other");
            File.WriteAllText(Path.Combine(_directoryPath, "file3.txt"), "not here");

            var zipFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".zip");

            ZipFile.CreateFromDirectory(_directoryPath, zipFilePath);
            return(zipFilePath);
        }
Exemplo n.º 6
0
        /// <summary>
        ///   Create file and folder structure for Profile.Generate() using variables from GenVars.
        /// </summary>
        /// <param name="path" >-path parameter to pass to Halo and write to profiles.</param>
        /// <param name="profile"   >Object to represent as string.</param>
        /// <param name="file"      >An instance of the File class</param>
        public static void Scaffold(string path, LastProfile lastprofile, Profile profile)
        {
            Core("Creating Scaffold...");

            /// Set Path to the -path parameter
            /// Check if it exists, create it if it doesn't.
            /// Print the full path to the console.
            /// e.g. ".\temp\"
            var file = (File)path;

            Directory.CreateDirectory(file.Path);
            VerifyPath(file.Path);

            /// Set Path to the savegames directory, et cetera
            file.Path = Custom.Profiles(path); /// e.g. ".\temp\savegames\
            Directory.CreateDirectory(file.Path);
            VerifyPath(file.Path);

            /// Set Path to the current Profile's directory, et cetera
            file.Path = Custom.ProfileDirectory(path, profile.Details.Name); /// e.g. ".\temp\savegames\New001\"
            Directory.CreateDirectory(file.Path);
            VerifyPath(file.Path);

            /// Create blam.sav
            file.Path = Custom.Profile(path, profile.Details.Name); /// e.g. ".\temp\savegames\New001\blam.sav"
            file.WriteAllBytes(new byte[8192]);
            VerifyPath(file.Path);

            /// Create savegame.bin
            file.Path = Custom.Progress(path, profile.Details.Name); /// e.g. ".\temp\savegames\New001\savegame.bin"
            file.WriteAllBytes(new byte[0x480000]);                  /// 0x480000 == int 4718592
            VerifyPath(file.Path);

            /// Create waypoint
            file.Path = Custom.Waypoint(path, profile.Details.Name); /// e.g. ".\temp\savegames\New001\New001"
            file.WriteAllText(Custom.Waypoint(path, profile.Details.Name));
            VerifyPath(file.Path);
            /// "waypoint" is used to refer to the file at "Path\\savegames\\Name\\Name"
            /// Halo writes the path of this file as the file's contents.
            /// For instance, `.\profiles\savegames\New001\New001`
            ///   when `-path .\profiles`

            /// Create or overwrite lastprof.txt
            file.Path = Custom.LastProfile(path);
            file.WriteAllBytes(new byte[0xFF]); /// 255 int. Makes room for up to 255 characters.
            lastprofile.Path = file.Path;
            lastprofile.Save();
            VerifyPath(file.Path);

            Info("Scaffold created.");
        }
Exemplo n.º 7
0
        public static string ServerCachePath(string accountToken)
        {
            var accountHash = MD5Helper.CalculateMd5Hash(accountToken);
            var fileName    = accountHash + CachingFileExt.ServerListExt;
            var cachePath   = $"{CachingFileDir.RootCacheDirectory}\\{accountHash}";

            if (!Directory.Exists(cachePath))
            {
                Directory.CreateDirectory(cachePath);
            }
            var fqPath = $"{cachePath}\\{fileName}";

            return(fqPath);
        }
Exemplo n.º 8
0
        private static void CopyFile(string copyPath, string fileName, string sourceFile)
        {
            if (!Directory.Exists(copyPath))
            {
                Directory.CreateDirectory(copyPath);
            }
            var newFile = Path.Combine(copyPath, fileName);

            if (!File.Exists(newFile))
            {
                File.Copy(sourceFile, newFile, true);
            }
            Console.WriteLine(sourceFile + " => " + Path.Combine(copyPath, fileName));
        }
Exemplo n.º 9
0
        private static void _organizeFile(Photo photo, string newOutPath, string prefix, bool rename, bool copy,
                                          OrganizeMethod method)
        {
            if (!photo.Renamable)
            {
                return;
            }

            string newPath = null;

            switch (method)
            {
            case OrganizeMethod.ByYear:
                newPath = $"{photo.GetYear()}";
                break;

            case OrganizeMethod.ByYearMonth:
                newPath = $"{photo.GetYear()}-{photo.GetMonth()}";
                break;

            case OrganizeMethod.ByMonthInYear:
                newPath = $"{photo.GetYear()}{Path.DirectorySeparatorChar}{photo.GetMonth()}";
                break;
            }

            newOutPath += Path.DirectorySeparatorChar + newPath + Path.DirectorySeparatorChar;

            if (!Directory.Exists(newOutPath))
            {
                Directory.CreateDirectory(newOutPath);
            }

            newOutPath += rename ? photo.GetShamsiName(prefix) : photo.FileName;

            try
            {
                if (copy)
                {
                    File.Copy(photo.FilePath, newOutPath);
                }
                else
                {
                    File.Move(photo.FilePath, newOutPath);
                }
            }
            catch (Exception e)
            {
                //TODO
            }
        }
Exemplo n.º 10
0
        private LfxBlob Add(Stream stream, LfxHash hash)
        {
            // insert
            var path = GetPath(hash);

            if (!File.Exists(path))
            {
                IODirectory.CreateDirectory(Path.GetDirectoryName(path));
                using (var targetStream = File.OpenWrite(path))
                    stream.CopyTo(targetStream);
            }

            return(new LfxBlob(this, hash, path));
        }
        public void Init()
        {
            var dir = Path.Combine(CurrentAssemblyDirectory, "TestData");

            if (Directory.Exists(dir))
            {
                Directory.GetDirectories("", "", SearchOption.AllDirectories);
                Directory.Delete(dir, true);
            }
            Directory.CreateDirectory(dir);
            Directory.CreateDirectory(Path.Combine(dir, "TempStorageDirectoryTests"));
            Directory.CreateDirectory(Path.Combine(dir, "TempStorageDirectoryTests", "RealStorage"));
            Directory.CreateDirectory(Path.Combine(dir, "TempStorageDirectoryTests", "TempStorage"));
        }
Exemplo n.º 12
0
 private void EnsureDirectoryExists()
 {
     try
     {
         if (!Directory.Exists(IndexPath))
         {
             Directory.CreateDirectory(IndexPath);
         }
     }
     catch (IOException ex)
     {
         throw new SearchException(ex, "An error occurred while creating the search directory '{0}'", IndexPath);
     }
 }
Exemplo n.º 13
0
        private string SaveFileName(string packageName)
        {
            string resolvedPath = null;

            try
            {
                if (!string.IsNullOrWhiteSpace(Path))
                {
                    resolvedPath = ResolveExistingFolderPath(Path, !Force);
                }

                if (!string.IsNullOrWhiteSpace(LiteralPath))
                {
                    // Validate that the path exists
                    try
                    {
                        SessionState.InvokeProvider.Item.Get(new string[] { LiteralPath }, false, true);
                    }
                    catch (ItemNotFoundException)
                    {
                        if (!Force)
                        {
                            throw;
                        }
                    }

                    resolvedPath = LiteralPath;
                }

                if (string.IsNullOrWhiteSpace(resolvedPath))
                {
                    Error(Constants.Errors.DestinationPathInvalid, resolvedPath, packageName);
                    return(null);
                }

                // If the destination directory doesn't exist, create it
                if (!Directory.Exists(resolvedPath))
                {
                    Directory.CreateDirectory(resolvedPath);
                }

                // don't append path and package name here
                return(resolvedPath);
            }
            catch (Exception e)
            {
                Error(Constants.Errors.SavePackageError, e.Message);
                return(null);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        ///     Extract the packs of a specific version from storage into a temporary directory.
        /// </summary>
        /// <param name="zip"><see cref="ZipFile" /> to read from.</param>
        /// <param name="previousVersion">Version of the packs to extract.</param>
        /// <returns>Returns the path to the directory containing the extracted packs.</returns>
        private static string ExtractPacks(ZipFile zip, string previousVersion)
        {
            var tempPath = Path.GetTempFileName();

            File.Delete(tempPath);
            Directory.CreateDirectory(tempPath);

            foreach (var entry in zip.Entries.Where(e => e.FileName.StartsWith(previousVersion)))
            {
                entry.Extract(tempPath);
            }

            return(tempPath);
        }
        protected void EnsureDirectoryExists(string directory, bool create = false)
        {
            if (IODirectory.Exists(directory))
            {
                return;
            }

            if (!create)
            {
                throw new InvalidOperationException($"The directory '{directory}' does not exists.");
            }

            IODirectory.CreateDirectory(directory);
        }
Exemplo n.º 16
0
        private static bool TryGetDiskCacheResult(string source, string name, InMemoryRavenConfiguration configuration, string indexFilePath,
                                                  out Type type)
        {
            // It's not in the in-memory cache. See if it's been cached on disk.
            //
            // Q. Why do we cache on disk?
            // A. It decreases the duration of individual test runs. Instead of
            //    recompiling the index each test run, we can just load them from disk.
            //    It also decreases creation time for indexes that were
            //    previously created and deleted, affecting both production and test environments.
            //
            // For more info, see http://ayende.com/blog/161218/robs-sprint-idly-indexing?key=f37cf4dc-0e5c-43be-9b27-632f61ba044f#comments-form-location
            var indexCacheDir = GetIndexCacheDir(configuration);

            try
            {
                if (Directory.Exists(indexCacheDir) == false)
                {
                    Directory.CreateDirectory(indexCacheDir);
                }
                type = TryGetIndexFromDisk(indexFilePath, name);
            }
            catch (UnauthorizedAccessException)
            {
                // permission issues
                type = null;
                return(false);
            }
            catch (IOException)
            {
                // permission issues, probably
                type = null;
                return(false);
            }

            if (type != null)
            {
                cacheEntries.TryAdd(source, new CacheEntry
                {
                    Source = source,
                    Type   = type,
                    Usages = 1
                });
                {
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 17
0
        public DirectoryBackup(string source, string destination, string tempPath)
        {
            this.source      = source;
            this.destination = destination;
            this.tempPath    = tempPath;

            if (Directory.Exists(tempPath) == false)
            {
                Directory.CreateDirectory(tempPath);
            }
            if (Directory.Exists(destination) == false)
            {
                Directory.CreateDirectory(destination);
            }
        }
 public static void AfterAccessNotification(TokenCacheNotificationArgs args)
 {
     // if the access operation resulted in a cache update
     if (args.TokenCache.HasStateChanged)
     {
         lock (FileLock)
         {
             // reflect changesgs in the persistent store
             Directory.CreateDirectory(Path.GetDirectoryName(CacheFilePath));
             File.WriteAllBytes(CacheFilePath, args.TokenCache.Serialize());
             // once the write operation takes place restore the HasStateChanged bit to filse
             args.TokenCache.HasStateChanged = false;
         }
     }
 }
Exemplo n.º 19
0
 /// <summary>
 /// Создает новый каталог.
 /// </summary>
 public override void create()
 {
     for (int i = 0; i < dirList.Count; i++)
     {
         try
         {
             ClassDir.CreateDirectory(dirList[i]);
             if (Messang != null)
             {
                 Messang(this, new MyEvenArgs(string.Format("Каталог '{0}' создан.", dirList[i])));
             }
         }
         catch { }
     }
 }
        private static void CreateDirectory(Directory directory, string path = ".")
        {
            var directoryPath = Path.Combine(path, directory.Name);
            var directoryInfo = DirectoryHelper.CreateDirectory(directoryPath);

            foreach (var file in directory.Files)
            {
                File.Create(Path.Combine(directoryPath, file))?.Dispose();
            }

            foreach (var subDirectory in directory.Directories)
            {
                CreateDirectory(subDirectory, directoryPath);
            }
        }
Exemplo n.º 21
0
 private static void CopyDirectory(DirectoryInfo source, string dest)
 {
     if (!Directory.Exists(dest))
     {
         Directory.CreateDirectory(dest);
     }
     foreach (var file in source.GetFiles())
     {
         file.CopyTo(Path.Combine(dest, file.Name));
     }
     foreach (var dir in source.GetDirectories())
     {
         CopyDirectory(dir, Path.Combine(dest, dir.Name));
     }
 }
Exemplo n.º 22
0
    /// Creates a prefab with materials
    private static void CreatePrefab(GameObject assetPrefab)
    {
        Selection.activeGameObject = assetPrefab;

        //Set the name of the object to be the prefab name
        assetPrefab.name = _assetName;

        //Save\Create the prefab in the project hierarchy
        var    folder         = Directory.CreateDirectory(PrefabPath);
        string prefabSavePath = string.Format("{0}/Prefabs/{1}_PF.prefab", _basePath, _assetName);

        PrefabUtility.SaveAsPrefabAsset(assetPrefab, prefabSavePath);

        GameObject.DestroyImmediate(assetPrefab);
    }
Exemplo n.º 23
0
        private void csvButton_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sb = new StringBuilder(mapPath);

            sb.Append(territoryName + @"\");

            String pathToSave = Environment.CurrentDirectory + "\\" + sb.ToString();

            if (!Directory.Exists(pathToSave))
            {
                Directory.CreateDirectory(pathToSave);
            }

            File.WriteAllText(pathToSave + "main.csv", maplist.ToString());
        }
Exemplo n.º 24
0
        public string CreateIndex()
        {
            //索引保存位置
            var indexPath = Directory.GetCurrentDirectory() + "/Index";

            if (!Directory.Exists(indexPath))
            {
                Directory.CreateDirectory(indexPath);
            }
            FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());

            if (IndexWriter.IsLocked(directory))
            {
                //  如果索引目录被锁定(比如索引过程中程序异常退出),则首先解锁
                //  Lucene.Net在写索引库之前会自动加锁,在close的时候会自动解锁
                IndexWriter.Unlock(directory);
            }
            //Lucene的index模块主要负责索引的创建
            //  创建向索引库写操作对象  IndexWriter(索引目录,指定使用盘古分词进行切词,最大写入长度限制)
            //  补充:使用IndexWriter打开directory时会自动对索引库文件上锁
            //IndexWriter构造函数中第一个参数指定索引文件存储位置;
            //第二个参数指定分词Analyzer,Analyzer有多个子类,
            //然而其分词效果并不好,这里使用的是第三方开源分词工具盘古分词;
            //第三个参数表示是否重新创建索引,true表示重新创建(删除之前的索引文件),
            //最后一个参数指定Field的最大数目。
            IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), true,
                                                 IndexWriter.MaxFieldLength.UNLIMITED);
            var txtPath = Directory.GetCurrentDirectory() + "/Upload/Articles";

            for (int i = 1; i <= 1000; i++)
            {
                //  一条Document相当于一条记录
                Document document = new Document();
                var      title    = "天骄战纪_" + i + ".txt";
                var      content  = System.IO.File.ReadAllText(txtPath + "/" + title, Encoding.Default);
                //  每个Document可以有自己的属性(字段),所有字段名都是自定义的,值都是string类型
                //  Field.Store.YES不仅要对文章进行分词记录,也要保存原文,就不用去数据库里查一次了
                document.Add(new Field("Title", "天骄战纪_" + i, Field.Store.YES, Field.Index.NOT_ANALYZED));
                //  需要进行全文检索的字段加 Field.Index. ANALYZED
                //  Field.Index.ANALYZED:指定文章内容按照分词后结果保存,否则无法实现后续的模糊查询
                //  WITH_POSITIONS_OFFSETS:指示不仅保存分割后的词,还保存词之间的距离
                document.Add(new Field("Content", content, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
                writer.AddDocument(document);
            }
            writer.Close();    // Close后自动对索引库文件解锁
            directory.Close(); //  不要忘了Close,否则索引结果搜不到
            return("索引创建完毕");
        }
Exemplo n.º 25
0
        /// <summary>
        /// Gets the date the file was taken, using EXIF data if available and the file creation date if not, and copies the file
        /// to a year and date directory within the appropriate destination folder. E.g., if a photo was taken July 4, 2020 and the
        /// destination photo directory is c:\photos, the file would be copied to c:\photos\2020\2020-07-04\.
        /// </summary>
        /// <param name="file">The file to copy.</param>
        public override async Task <Result> ProcessAsync(string file)
        {
            DateTime created;

            var exifDate = ImageMetadataReader.ReadMetadata(file).OfType <ExifSubIfdDirectory>().FirstOrDefault()?.GetDescription(ExifDirectoryBase.TagDateTime);

            if (exifDate == null || !DateTime.TryParseExact(exifDate, "yyyy:MM:dd HH:mm:ss", CultureInfo.CurrentCulture, DateTimeStyles.None, out created))
            {
                created = File.GetCreationTime(file);
            }

            var destFile = Path.Combine(IsPhoto(file) ? Config.PhotoDestination : Config.VideoDestination, created.Year.ToString(), created.ToString("yyyy-MM-dd"), Path.GetFileName(file));

            if (File.Exists(destFile))
            {
                return(Result.Success("Already Exists"));
            }

            using (var source = File.Open(file, FileMode.Open))
            {
                var destDir = Path.GetDirectoryName(destFile);

                if (!Config.Preview)
                {
                    if (!IODirectory.Exists(destDir))
                    {
                        IODirectory.CreateDirectory(destDir);
                    }

                    using var dest = File.Create(destFile);

                    await source.CopyToAsync(dest, CancellationToken);
                }
                else
                {
                    return(Result.Success("To Be Copied", destFile));
                }
            }

            if (CancellationToken.IsCancellationRequested)
            {
                return(Result.SuccessOrCancelled(CancellationToken));
            }
            else
            {
                return(Result.Success("Copied"));
            }
        }
Exemplo n.º 26
0
        public LuceneIndexManager(
            IHostingEnvironment hostingEnvironment,
            IOptions <ShellOptions> shellOptions,
            ShellSettings shellSettings
            )
        {
            _hostingEnvironment = hostingEnvironment;

            _rootPath = Path.Combine(
                _hostingEnvironment.ContentRootPath,
                shellOptions.Value.ShellsRootContainerName,
                shellOptions.Value.ShellsContainerName,
                shellSettings.Name, "Lucene");

            _rootDirectory = Directory.CreateDirectory(_rootPath);
        }
Exemplo n.º 27
0
        private void AddDirectoryToScan(string directory)
        {
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            FileSystemWatcher watcher = new FileSystemWatcher(directory);

            watcher.Created += (sender, eventArgs) =>
            {
                this.OnFileCreated(eventArgs.Name, eventArgs.FullPath);
            };

            watcher.EnableRaisingEvents = true;
        }
        public void GetSubFolders_ShouldReturnSubFolders_WhenPathIsCorrect()
        {
            var imageFileBuilderMock = new Mock <IImageFileBuilder>();
            var directory            = "3D2DCE88-3524-4CB7-9311-47864BC0DAEE\\";
            var subFolder1           = "Folder1";
            var subFolder2           = "Folder2";

            Directory.CreateDirectory(TestFolder + directory + subFolder1);
            Directory.CreateDirectory(TestFolder + directory + subFolder2);

            var service = new DirectoryService(imageFileBuilderMock.Object);
            var folders = service.GetSubFolders(TestFolder + directory);

            Assert.Contains(folders, x => x.Name == subFolder1);
            Assert.Contains(folders, x => x.Name == subFolder2);
        }
Exemplo n.º 29
0
        public LuceneIndexManager(
            IClock clock,
            IOptions <ShellOptions> shellOptions,
            ShellSettings shellSettings,
            ILogger <LuceneIndexManager> logger
            )
        {
            _clock    = clock;
            _logger   = logger;
            _rootPath = Path.Combine(
                shellOptions.Value.ShellsApplicationDataPath,
                shellOptions.Value.ShellsContainerName,
                shellSettings.Name, "Lucene");

            _rootDirectory = Directory.CreateDirectory(_rootPath);
        }
        private void TransferFile(string from, string to)
        {
            string directoryName = Path.GetDirectoryName(to);

            if (!Dir.Exists(directoryName))
            {
                Dir.CreateDirectory(directoryName);
            }

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

            File.Move(from, to);
        }