コード例 #1
0
        /// <summary>
        /// Creates all directories and subdirectories in the specified path unless they already exist.
        /// </summary>
        /// <param name="path">The directory to create.</param>
        public static void CreateDirectory(string path)
        {
#if DOTNET5_4
            Directory.CreateDirectory(path);
#else
            LongPathDirectory.CreateDirectory(path);
#endif
        }
コード例 #2
0
        public static bool Exists(string path)
        {
#if DOTNET5_4
            return(Directory.Exists(path));
#else
            return(LongPathDirectory.Exists(path));
#endif
        }
コード例 #3
0
 public static void Create(string path)
 {
     if (path.Length < MAX_PATH)
     {
         System.IO.Directory.CreateDirectory(path);
     }
     else
     {
         LongPathDirectory.Create(path);
     }
 }
コード例 #4
0
 public override void Delete()
 {
     if (IsHardLink)
     {
         JunctionPoint.Delete(Path);
     }
     else
     {
         LongPathDirectory.Delete(Path, true);
     }
 }
コード例 #5
0
 public static string[] GetFiles(string path)
 {
     if (path.Length < MAX_PATH)
     {
         return(System.IO.Directory.GetFiles(path));
     }
     else
     {
         return(LongPathDirectory.EnumerateFiles(path).ToArray());
     }
 }
コード例 #6
0
 public static bool Exists(string path)
 {
     if (path.Length < MAX_PATH)
     {
         return(System.IO.Directory.Exists(path));
     }
     else
     {
         return(LongPathDirectory.Exists(path));
     }
 }
コード例 #7
0
        /// <summary>
        /// Refreshes the state of the object.
        /// </summary>
        /// <exception cref="IOException">A device such as a disk drive is not ready.</exception>
        public void Refresh()
        {
            List <Win32FindData> foundFiles = LongPathDirectory.EnumerateFileSystemIterator(
                LongPathCommon.GetDirectoryName(this.normalizedPath),
                Path.GetFileName(this.normalizedPath),
                SearchOption.TopDirectoryOnly,
                this.isDirectory,
                !this.isDirectory).ToList();

            this.entryData   = foundFiles.Count > 0 ? foundFiles[0] : (Win32FindData?)null;
            this.initialized = true;
        }
        public static bool Exists(string path)
        {
#if DOTNET5_4
            return(Directory.Exists(path));
#else
            if (DMLibTestConstants.SupportUNCPath)
            {
                path = LongPath.ToUncPath(path);
            }
            return(LongPathDirectory.Exists(path));
#endif
        }
コード例 #9
0
        /// <summary>
        ///     Determines whether the specified path exists and refers to a junction point.
        /// </summary>
        /// <param name = "path">The junction point path</param>
        /// <returns>True if the specified path represents a junction point</returns>
        /// <exception cref = "IOException">Thrown if the specified path is invalid
        ///     or some other error occurs</exception>
        public static bool Exists(Path path)
        {
            if (!LongPathDirectory.Exists(path))
            {
                return(false);
            }

            using (var handle = OpenReparsePoint(path, EFileAccess.GenericRead))
            {
                var target = InternalGetTarget(handle);
                return(target != null);
            }
        }
コード例 #10
0
 public static void Delete(string path)
 {
     if (path.Length < MAX_PATH)
     {
         System.IO.Directory.Delete(path, true);
     }
     else
     {
         // NOTE: recursive isn't available on the longpath yet, so we only do this if we have to
         //TODO: implement the recursive stuff ourself
         LongPathDirectory.Delete(path);
     }
 }
コード例 #11
0
        static IEnumerable <Directory> DirectoriesRecurse(FileSystem fs, Directory directory, string filter)
        {
            // TODO: needs to be replaced with a cross-platform enumeration
            foreach (var topDir in LongPathDirectory.EnumerateDirectories(directory.Path, filter))
            {
                foreach (var subDir in DirectoriesRecurse(fs, fs.GetDirectory(topDir), filter))
                {
                    yield return(subDir);
                }

                yield return(fs.CreateDirectory(topDir));
            }
        }
            public override void DeleteDirectory(string directoryPath)
            {
                foreach (string subdirectoryPathToDelete in EnumerateDirectories(directoryPath))
                {
                    DeleteDirectory(subdirectoryPathToDelete);
                }

                foreach (string filePathToDelete in EnumerateFiles(directoryPath))
                {
                    DeleteFile(filePathToDelete);
                }

                LongPathDirectory.Delete(directoryPath);
            }
コード例 #13
0
        /// <summary>
        ///     Deletes a junction point at the specified source directory along with the directory itself.
        ///     Does nothing if the junction point does not exist.
        /// </summary>
        /// <remarks>
        ///     Only works on NTFS.
        /// </remarks>
        /// <param name = "junctionPoint">The junction point path</param>
        public static void Delete(Path junctionPoint)
        {
            if (!LongPathDirectory.Exists(junctionPoint))
            {
                if (LongPathFile.Exists(junctionPoint))
                {
                    throw new IOException("Path is not a junction point.");
                }

                return;
            }

            using (var handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericWrite))
            {
                var reparseDataBuffer = new REPARSE_DATA_BUFFER();

                reparseDataBuffer.ReparseTag        = IO_REPARSE_TAG_MOUNT_POINT;
                reparseDataBuffer.ReparseDataLength = 0;
                reparseDataBuffer.PathBuffer        = new byte[0x3ff0];

                var inBufferSize = Marshal.SizeOf(reparseDataBuffer);
                var inBuffer     = Marshal.AllocHGlobal(inBufferSize);
                try
                {
                    Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);

                    int bytesReturned;
                    var result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_DELETE_REPARSE_POINT,
                                                 inBuffer, 8, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);

                    if (!result)
                    {
                        ThrowLastWin32Error("Unable to delete junction point.");
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(inBuffer);
                }

                try
                {
                    LongPathDirectory.Delete(junctionPoint);
                }
                catch (IOException ex)
                {
                    throw new IOException("Unable to delete junction point.", ex);
                }
            }
        }
コード例 #14
0
        private void OnFileSystemEntriesListBoxMouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (fileSystemEntriesListBox.SelectedItem != null)
            {
                string path = (string)fileSystemEntriesListBox.SelectedItem;

                if (LongPathDirectory.Exists(path))
                {
                    this.currentPath.Text = path;
                }

                RefreshFileList();
            }
        }
コード例 #15
0
        void IDirectoryAdapter.Delete(string path)
        {
            AssertAllowed(path);
#if !MONO
            var mTx = CurrentTransaction();
            if (mTx.HasValue)
            {
                ((IDirectoryAdapter)mTx.Value).Delete(path);
                return;
            }
#endif

            LongPathDirectory.Delete(path);
        }
コード例 #16
0
        bool IDirectoryAdapter.Exists(string path)
        {
            AssertAllowed(path);

#if !MONO
            var mTx = CurrentTransaction();
            if (mTx.HasValue)
            {
                return(((IDirectoryAdapter)mTx.Value).Exists(path));
            }
#endif

            return(LongPathDirectory.Exists(path));
        }
コード例 #17
0
        /// <summary>
        /// Delete non empty directory tree
        /// </summary>
        private void DeleteDirectory(string target_dir)
        {
            string[] files = Directory.GetFiles(target_dir);
            string[] dirs  = Directory.GetDirectories(target_dir);

            foreach (string file in files)
            {
                try
                {
                    File.SetAttributes(file, FileAttributes.Normal);
                    File.Delete(file);
                }
                catch (PathTooLongException)
                {
                    LongPathFile.Delete(file);
                }
            }

            foreach (string dir in dirs)
            {
                // Only recurse into "normal" directories
                if ((File.GetAttributes(dir) & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)
                {
                    try
                    {
                        Directory.Delete(dir, false);
                    }
                    catch (PathTooLongException)
                    {
                        LongPathDirectory.Delete(dir);
                    }
                }
                else
                {
                    DeleteDirectory(dir);
                }
            }

            try
            {
                Directory.Delete(target_dir, false);
            }
            catch (PathTooLongException)
            {
                LongPathDirectory.Delete(target_dir);
            }
        }
        /// <summary>
        /// Creates all directories and subdirectories in the specified path unless they already exist.
        /// </summary>
        /// <param name="path">The directory to create.</param>
        public static void CreateDirectory(string path)
        {
            try
            {
                path = DMLibTestConstants.SupportUNCPath ?
                       LongPath.GetFullPath(LongPath.ToUncPath(path)) :
                       LongPath.GetFullPath(path);
            }
            catch (Exception)
            { }

#if DOTNET5_4
            Directory.CreateDirectory(path);
#else
            LongPathDirectory.CreateDirectory(path);
#endif
        }
コード例 #19
0
        protected override async Task <bool> DoWorkInternalAsync()
        {
            status = Status.Started;

            await Task.Run(
                () =>
            {
                if (this.TransferJob.Source.Type == TransferLocationType.AzureBlob &&
                    this.TransferJob.Destination.Type == TransferLocationType.FilePath)
                {
                    // Dummy transfer for downloading dummy blobs.
                    var filePath = (this.TransferJob.Destination as FileLocation).FilePath.ToLongPath();

                    if (LongPathFile.Exists(filePath))
                    {
                        string exceptionMessage = string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.FailedToCreateDirectoryException,
                            filePath);

                        throw new TransferException(
                            TransferErrorCode.FailedToCreateDirectory,
                            exceptionMessage);
                    }
                    else
                    {
                        LongPathDirectory.CreateDirectory(filePath);
                    }
                }
                // Hint: adding new dummy directions here.
                else
                {
                    string exceptionMessage = string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.UnsupportedDummyTransferException);

                    throw new TransferException(
                        TransferErrorCode.UnsupportedDummyTransfer,
                        exceptionMessage);
                }

                status = Status.Finished;
            }, this.CancellationToken);

            return(status == Status.Finished || status == Status.ErrorOccured);
        }
コード例 #20
0
        bool IDirectoryAdapter.Delete(string path, bool recursively)
        {
            AssertAllowed(path);
#if !MONO
            var mTx = CurrentTransaction();
            if (mTx.HasValue)
            {
                return(((IDirectoryAdapter)mTx.Value).Delete(path, recursively));
            }
#endif

            // because of http://stackoverflow.com/questions/3764072/c-win32-how-to-wait-for-a-pending-delete-to-complete

            var target = Path.GetRandomFileName();
            LongPathDirectory.Move(path, target);
            LongPathDirectory.Delete(target, recursively);
            return(true);
        }
            public override IEnumerable <string> EnumerateFiles(string path, string searchPattern = "*", bool recursive = false)
            {
                foreach (string file in LongPathDirectory.EnumerateFiles(path, searchPattern))
                {
                    yield return(file);
                }

                if (recursive)
                {
                    foreach (string directory in EnumerateDirectories(path, searchPattern, recursive: false))
                    {
                        foreach (string file in EnumerateFiles(directory, searchPattern, recursive: true))
                        {
                            yield return(file);
                        }
                    }
                }
            }
コード例 #22
0
        private void OnCreateDirectoryButtonClick(object sender, EventArgs e)
        {
            try {
                string path = Path.Combine(this.currentPath.Text, fileNameTextBox.Text);
                LongPathDirectory.Create(path);
            }
            catch (ArgumentException ex) {
                ShowError(ex);
            }
            catch (IOException ex) {
                ShowError(ex);
            }
            catch (UnauthorizedAccessException ex) {
                ShowError(ex);
            }

            RefreshFileList();
        }
コード例 #23
0
ファイル: TestUnzip.cs プロジェクト: frenzqse/loom-csharp
        private void DeleteAllFolder(String parentDirectory)
        {
            if (parentDirectory == null)
            {
                return;
            }

            foreach (String file in LongPathDirectory.EnumerateFiles(parentDirectory))
            {
                LongPathFile.Delete(file);
            }

            foreach (String info in LongPathDirectory.EnumerateDirectories(parentDirectory))
            {
                this.DeleteAllFolder(info);
            }

            Microsoft.Experimental.IO.LongPathDirectory.Delete(parentDirectory);
        }
コード例 #24
0
 private static void LoadConfigurations(string path)
 {
     if (string.IsNullOrEmpty(path))
     {
         path = LongPath.Combine(AssemblyExtensions.ApplicationDirectory, "WebServiceLibraries");
     }
     try
     {
         var allFiles = LongPathDirectory.EnumerateFiles(path, "*.config", System.IO.SearchOption.AllDirectories);
         foreach (var file in allFiles)
         {
             try
             {
                 var info    = WebServiceRegistrationInfo.LoadFromFile(file);
                 var gllName = LongPath.ChangeExtension(file, ".gll");
                 if (info.RegisteredVIs != null)
                 {
                     foreach (var item in info.RegisteredVIs)
                     {
                         if (item.Type == WebServiceType.HttpGetMethod)
                         {
                             var registeredExecutable = new RegisteredHttpGetVI(
                                 _connectionManager,
                                 _httpServer,
                                 gllName,
                                 item.VIComponentName,
                                 item.UrlPath);
                             _connectionManager.AddConnectionType(registeredExecutable);
                         }
                     }
                 }
             }
             catch (Exception e)
             {
                 Log.LogError(0, e, $"Failed to load configuration: {file}");
             }
         }
     }
     catch (Exception enumerateException)
     {
         Log.LogError(0, enumerateException, "Failed to enumerate configuration files");
     }
 }
            public override IEnumerable <string> EnumerateDirectories(string path, string searchPattern = "*", bool recursive = false)
            {
                IEnumerable <string> directories = LongPathDirectory.EnumerateDirectories(path, searchPattern);

                foreach (string directory in directories)
                {
                    yield return(directory);
                }

                if (recursive)
                {
                    foreach (string directory in directories)
                    {
                        foreach (string subdirectory in EnumerateDirectories(directory, searchPattern, recursive: true))
                        {
                            yield return(subdirectory);
                        }
                    }
                }
            }
コード例 #26
0
ファイル: PathTool.cs プロジェクト: 1269085759/up6-asp.net
        /// <summary>
        /// 自动创建多层级路径
        /// </summary>
        /// <param name="path"></param>
        /// <param name="separator">路径分隔符,默认:/</param>
        public static void createDirectory(string path, char separator = '/')
        {
            var dirs   = path.Split(separator);
            var folder = "";

            foreach (var dir in dirs)
            {
                if (folder != "")
                {
                    folder = folder + "/" + dir;
                }
                else
                {
                    folder = dir;
                }
                if (!LongPathDirectory.Exists(folder))
                {
                    LongPathDirectory.Create(folder);
                }
                System.Diagnostics.Debug.WriteLine(folder);
            }
        }
コード例 #27
0
        private void OnDeleteButtonClick(object sender, EventArgs e)
        {
            string selectedPath = (string)fileSystemEntriesListBox.SelectedItem;

            try {
                if (LongPathDirectory.Exists(selectedPath))
                {
                    LongPathDirectory.Delete(selectedPath);
                }
                else
                {
                    LongPathFile.Delete(selectedPath);
                }
            }
            catch (IOException ex) {
                ShowError(ex);
            }
            catch (UnauthorizedAccessException ex) {
                ShowError(ex);
            }

            RefreshFileList();
        }
コード例 #28
0
        public static IEnumerable <string> EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption, LongPathDirectory.FilesOrDirectory filter = LongPathDirectory.FilesOrDirectory.All)
        {
            return(LongPathDirectory.EnumerateFileSystemEntries(path, searchPattern, searchOption, filter));
#endif
        }
コード例 #29
0
        /// <summary>
        /// Creates a new <c>LazyCopy</c> file.
        /// </summary>
        /// <param name="path">Path to the reparse point to get data from.</param>
        /// <param name="fileData">Reparse file data to be set for the <paramref name="path"/>.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="path"/> is <see langword="null"/> or empty.
        ///     <para>-or-</para>
        /// <paramref name="fileData"/> is <see langword="null"/>.
        ///     <para>-or-</para>
        /// <paramref name="fileData"/> contains <see langword="null"/> or empty file path.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="fileData"/> contains negative file size.</exception>
        /// <exception cref="IOException">File cannot be created.</exception>
        /// <exception cref="InvalidOperationException">Reparse point data cannot be set.</exception>
        public static void CreateLazyCopyFile(string path, LazyCopyFileData fileData)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (fileData == null)
            {
                throw new ArgumentNullException(nameof(fileData));
            }

            if (string.IsNullOrEmpty(fileData.RemotePath))
            {
                throw new ArgumentNullException(nameof(fileData));
            }

            if (fileData.FileSize < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(fileData), fileData.FileSize, "File size is negative.");
            }

            string           normalizedPath = LongPathCommon.NormalizePath(path);
            LongPathFileInfo fileInfo       = new LongPathFileInfo(normalizedPath);

            bool shouldCreateFile = false;

            if (!fileInfo.Exists || fileInfo.Length > 0)
            {
                LongPathDirectory.CreateDirectory(fileInfo.DirectoryName);
                shouldCreateFile = true;
            }
            else if (!fileInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))
            {
                shouldCreateFile = true;
            }
            else if (fileInfo.Attributes.HasFlag(FileAttributes.ReadOnly))
            {
                fileInfo.Attributes &= ~FileAttributes.ReadOnly;
            }

            if (shouldCreateFile)
            {
                using (fileInfo.Create())
                {
                    // Do nothing.
                }
            }

            // If the original file is empty, we don't need to set a reparse point for it.
            if (fileData.FileSize == 0)
            {
                return;
            }

            ReparsePointHelper.SetReparsePointData(
                path,
                new object[] // Custom serialization layout for the LazyCopyFileData object.
            {
                (long)(fileData.UseCustomHandler ? 1L : 0L),
                (long)fileData.FileSize,
                // Add the prefix, if the custom handling is needed for the file.
                Encoding.Unicode.GetBytes(
                    (fileData.UseCustomHandler ? fileData.RemotePath : PathHelper.ChangeDriveLetterToDeviceName(fileData.RemotePath))
                    + '\0')
            },
                LazyCopyFileHelper.LazyCopyReparseTag,
                LazyCopyFileHelper.LazyCopyReparseGuid);

            // Set the proper file attributes.
            LongPathCommon.SetAttributes(path, FileAttributes.ReparsePoint | FileAttributes.NotContentIndexed | FileAttributes.Offline);
        }
コード例 #30
0
        public static IEnumerable <string> EnumerateFiles(
            string path,
            string searchPattern,
            string fromFilePath,
            SearchOption searchOption,
            bool followsymlink,
            CancellationToken cancellationToken)
        {
            Utils.CheckCancellation(cancellationToken);

            if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
            {
                throw new ArgumentOutOfRangeException("searchOption");
            }

            // Remove whitespaces in the end.
            searchPattern = searchPattern.TrimEnd();
            if (searchPattern.Length == 0)
            {
                // Returns an empty string collection.
                return(new List <string>());
            }

            // To support patterns like "folderA\" aiming at listing files under some folder.
            if ("." == searchPattern)
            {
                searchPattern = "*";
            }

            Utils.CheckCancellation(cancellationToken);

            CheckSearchPattern(searchPattern);

            Utils.CheckCancellation(cancellationToken);

            // Check path permissions.
            string fullPath = null;

            if (Interop.CrossPlatformHelpers.IsWindows)
            {
                fullPath = LongPath.ToUncPath(path);
            }
            else
            {
                fullPath = Path.GetFullPath(path);
            }
#if CODE_ACCESS_SECURITY
            CheckPathDiscoveryPermission(fullPath);
#endif // CODE_ACCESS_SECURITY

            string patternDirectory = LongPath.GetDirectoryName(searchPattern);
#if CODE_ACCESS_SECURITY
            if (!string.IsNullOrEmpty(patternDirectory))
            {
                CheckPathDiscoveryPermission(LongPath.Combine(fullPath, patternDirectory));
            }
#endif // CODE_ACCESS_SECURITY

            if (!string.IsNullOrEmpty(fromFilePath) &&
                !string.IsNullOrEmpty(patternDirectory))
            {
                // if file pattern is like folder\fileName*, we'll list location\folder with pattern fileName*
                // but the listted relative path will still be like folder\fileName1, and the continuation token will look the same.
                // Then here we need to make continuation token to be path relative to location\folder.
                string tmpPatternDir = AppendDirectorySeparator(patternDirectory);
                fromFilePath = fromFilePath.Substring(tmpPatternDir.Length);
            }

            string fullPathWithPattern = LongPath.Combine(fullPath, searchPattern);

            // To support patterns like "folderA\" aiming at listing files under some folder.
            char lastC = fullPathWithPattern[fullPathWithPattern.Length - 1];
            if (Path.DirectorySeparatorChar == lastC ||
                Path.AltDirectorySeparatorChar == lastC ||
                Path.VolumeSeparatorChar == lastC)
            {
                fullPathWithPattern = fullPathWithPattern + '*';
            }

            string directoryName = AppendDirectorySeparator(LongPath.GetDirectoryName(fullPathWithPattern));
            string filePattern   = fullPathWithPattern.Substring(directoryName.Length);

            if (!LongPathDirectory.Exists(directoryName))
            {
                throw new DirectoryNotFoundException(
                          string.Format(
                              CultureInfo.CurrentCulture,
                              Resources.PathNotFound,
                              directoryName));
            }

            Utils.CheckCancellation(cancellationToken);
            return(InternalEnumerateFiles(directoryName, filePattern, fromFilePath, searchOption, followsymlink, cancellationToken));
        }