Beispiel #1
0
        /// <summary>
        /// 根据文件大小创建文件。
        /// 注意:多个用户同时上传相同文件时,可能会同时创建相同文件。
        /// </summary>
        public void make(string filePath, long len)
        {
            //文件不存在则创建
            if (string.IsNullOrEmpty(filePath))
            {
                return;
            }
            if (!LongPathFile.Exists(filePath))
            {
                var pos = filePath.LastIndexOf('\\');
                if (-1 == pos)
                {
                    pos = filePath.LastIndexOf('/');
                }
                var dir = filePath.Substring(0, pos);
                //自动创建目录
                if (!LongPathDirectory.Exists(dir))
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("路径不存在:{0}", dir));
                    PathTool.createDirectory(dir);
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("路径存在:{0}", dir));
                }

                var fs = LongPathFile.Open(filePath, FileMode.Create, FileAccess.Write);
                fs.SetLength(len);
                fs.Close();
            }
        }
Beispiel #2
0
 public override void Delete()
 {
     if (LongPathFile.Exists(Path))
     {
         LongPathFile.Delete(Path);
     }
 }
Beispiel #3
0
 private void ThrowIfProjectPathDoesNotExist()
 {
     if (!LongPathFile.Exists(ProjectPath))
     {
         string message = string.Format(
             CultureInfo.CurrentCulture,
             LocalizedStrings.BuildComponentTool_InvalidProjectPath,
             ProjectPath);
         throw new CommandLineOperationException(message, showToolHelp: true);
     }
 }
Beispiel #4
0
 public static bool Exists(string path)
 {
     if (path.Length < MAX_PATH)
     {
         return(System.IO.File.Exists(path));
     }
     else
     {
         return(LongPathFile.Exists(path));
     }
 }
        ///<summary>
        ///	Returns whether the specified file exists or not.
        ///</summary>
        ///<param name = "filePath">The file path.</param>
        ///<returns></returns>
        public bool Exists(string filePath)
        {
            AssertAllowed(filePath);
#if !MONO
            var mTx = CurrentTransaction();
            if (mTx.HasValue)
            {
                return(((IFileAdapter)mTx.Value).Exists(filePath));
            }
#endif
            return(LongPathFile.Exists(filePath));
        }
Beispiel #6
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);
                }
            }
        }
Beispiel #7
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);
        }
Beispiel #8
0
 public static void Delete(string path)
 {
     if (path.Length < MAX_PATH)
     {
         if (File.Exists(path))
         {
             System.IO.File.Delete(path);
         }
     }
     else
     {
         if (LongPathFile.Exists(path))
         {
             LongPathFile.Delete(path);
         }
     }
 }
Beispiel #9
0
        /// <summary>
        /// Generates unique file name in the <paramref name="parentDirectory"/>.
        /// </summary>
        /// <param name="parentDirectory">Directory, where the file will be stored into.</param>
        /// <param name="prefix">File prefix. May be <see langword="null"/>.</param>
        /// <param name="extension">File extension. May be <see langword="null"/>.</param>
        /// <returns>Path to the file.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="parentDirectory"/> is <see langword="null"/>.</exception>
        /// <remarks>
        /// The result file name will look like the following: <c>&lt;prefix&gt;&lt;GUID&gt;.&lt;extension&gt;</c><br/>
        /// For example:<br/>
        /// <code>
        ///     PathHelper.GenerateUniqueFileName(@"C:\Temp\", "a_", "bin");  // C:\Temp\a_8F3C680522E0457896837ADF38ED8E6A.bin
        ///     PathHelper.GenerateUniqueFileName(@"C:\Temp\", "b_", ".txt"); // C:\Temp\b_BF3C086BE0C444B4906E4A36CBC16551.txt
        /// </code>
        /// </remarks>
        public static string GenerateUniqueFileName(string parentDirectory, string prefix, string extension)
        {
            if (string.IsNullOrEmpty(parentDirectory))
            {
                throw new ArgumentNullException(nameof(parentDirectory));
            }

            prefix = string.IsNullOrWhiteSpace(prefix) ? string.Empty : prefix.Trim();

            extension = extension?.Trim().TrimStart('.') ?? string.Empty;
            extension = string.IsNullOrEmpty(extension) ? string.Empty : "." + extension;

            string result;

            do
            {
                result = Path.Combine(parentDirectory, prefix + Guid.NewGuid().ToString("N") + extension);
            }while (LongPathFile.Exists(result));

            return(result);
        }
        public void Run_PathIsVeryLong_DoesCopy()
        {
            //we're adding this guid because teh normal tempfolder code can't handle this super deap thing, can't clear it out for us
            //as we re-run this test
            var guid = Guid.NewGuid().ToString();

            using (var from = new TemporaryFolder("synctest_source" + guid))
                using (var to = new TemporaryFolder("synctest_dest" + guid))
                {
                    string sub = from.Path;
                    for (int i = 0; i < 10; i++)
                    {
                        sub = sub + Path.DirectorySeparatorChar + "OnePartOfTheDirectory" + i;
                        Microsoft.Experimental.IO.LongPathDirectory.Create(sub);
                    }

                    var fileName = "1.txt";
                    using (var file = Microsoft.Experimental.IO.LongPathFile.Open(sub.CombineForPath(fileName), FileMode.CreateNew,
                                                                                  FileAccess.ReadWrite))
                    {
                    }
                    var source   = new RawDirectoryGroup("Group1", from.Path, null, null);
                    var groups   = new List <FileGroup>(new[] { source });
                    var progress = new ConsoleProgress()
                    {
                        ShowVerbose = true
                    };

                    var sync = new MirrorController(to.Path, groups, 100, progress);

                    sync.Run();
                    string path = sub.Replace("synctest_source" + guid, "synctest_dest" + guid + Path.DirectorySeparatorChar + "Group1").CombineForPath("1.txt");

                    Assert.That(LongPathFile.Exists(path), path);
                }
        }
        private async Task HandleOutputStreamAsync()
        {
            this.hasWork = false;

            await Task.Run(async() =>
            {
                // Only do calculation related to transfer window when the file contains multiple chunks.
                if (!this.EnableOneChunkFileOptimization)
                {
                    // We do check point consistancy validation in reader, and directly use it in writer.
                    if ((null != this.TransferJob.CheckPoint.TransferWindow) &&
                        this.TransferJob.CheckPoint.TransferWindow.Any())
                    {
                        this.TransferJob.CheckPoint.TransferWindow.Sort();
                        this.expectOffset = this.TransferJob.CheckPoint.TransferWindow[0];
                    }
                    else
                    {
                        this.expectOffset = this.TransferJob.CheckPoint.EntryTransferOffset;
                    }
                }

                if (TransferLocationType.Stream == this.TransferJob.Destination.Type)
                {
                    Stream streamInDestination = (this.TransferJob.Destination as StreamLocation).Stream;
                    if (!streamInDestination.CanWrite)
                    {
                        throw new NotSupportedException(string.Format(
                                                            CultureInfo.CurrentCulture,
                                                            Resources.StreamMustSupportWriteException,
                                                            "outputStream"));
                    }

                    if (!streamInDestination.CanSeek)
                    {
                        throw new NotSupportedException(string.Format(
                                                            CultureInfo.CurrentCulture,
                                                            Resources.StreamMustSupportSeekException,
                                                            "outputStream"));
                    }

                    this.outputStream = streamInDestination;
                }
                else
                {
                    string filePath = (this.TransferJob.Destination as FileLocation).FilePath;

                    if (!this.Controller.IsForceOverwrite)
                    {
                        await this.Controller.CheckOverwriteAsync(
                            LongPathFile.Exists(filePath),
                            this.TransferJob.Source.Instance,
                            filePath);
                    }

                    this.Controller.CheckCancellation();

                    try
                    {
                        FileMode fileMode = 0 == this.expectOffset ? FileMode.OpenOrCreate : FileMode.Open;

#if DOTNET5_4
                        string longFilePath = filePath;
                        if (Interop.CrossPlatformHelpers.IsWindows)
                        {
                            longFilePath = LongPath.ToUncPath(longFilePath);
                        }

                        // Attempt to open the file first so that we throw an exception before getting into the async work
                        this.outputStream = new FileStream(
                            longFilePath,
                            fileMode,
                            FileAccess.ReadWrite,
                            FileShare.None);
#else
                        this.outputStream = LongPathFile.Open(
                            filePath,
                            fileMode,
                            FileAccess.ReadWrite,
                            FileShare.None);
#endif

                        this.ownsStream = true;
                    }
                    catch (Exception ex)
                    {
                        string exceptionMessage = string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.FailedToOpenFileException,
                            filePath,
                            ex.Message);

                        throw new TransferException(
                            TransferErrorCode.OpenFileFailed,
                            exceptionMessage,
                            ex);
                    }
                }

                this.outputStream.SetLength(this.SharedTransferData.TotalLength);

                this.md5HashStream = new MD5HashStream(
                    this.outputStream,
                    this.expectOffset,
                    !this.SharedTransferData.DisableContentMD5Validation);

                if (this.md5HashStream.FinishedSeparateMd5Calculator)
                {
                    this.state = State.Write;
                }
                else
                {
                    this.state = State.CalculateMD5;
                }

                this.PreProcessed = true;

                // Switch state internal for one chunk small file.
                if (this.EnableOneChunkFileOptimization &&
                    State.Write == this.state &&
                    ((this.SharedTransferData.TotalLength == this.expectOffset) || this.SharedTransferData.AvailableData.ContainsKey(this.expectOffset)))
                {
                    this.isStateSwitchedInternal = true;
                    await this.WriteChunkDataAsync().ConfigureAwait(false);
                }
                else
                {
                    this.hasWork = true;
                }
            });
        }
Beispiel #12
0
 public override bool Exists()
 {
     return(LongPathFile.Exists(Path));
 }
 public override bool FileExists(string filePath)
 {
     return(LongPathFile.Exists(filePath));
 }