Exemple #1
0
        /// <summary>
        /// Provides a common way for opening a file stream for exclusively deleting the file.
        /// </summary>
        private static Stream GetFileDeleteStream(FileInfoBase file)
        {
            Contract.Assert(file != null);

            // Open file exclusively for delete sharing only
            return(file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete));
        }
        public static void Extract(this ZipArchive archive, string directoryName)
        {
            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                string path = Path.Combine(directoryName, entry.FullName);
                if (entry.Length == 0 && (path.EndsWith("/", StringComparison.Ordinal) || path.EndsWith("\\", StringComparison.Ordinal)))
                {
                    // Extract directory
                    FileSystemHelpers.CreateDirectory(path);
                }
                else
                {
                    FileInfoBase fileInfo = FileSystemHelpers.FileInfoFromFileName(path);

                    if (!fileInfo.Directory.Exists)
                    {
                        fileInfo.Directory.Create();
                    }

                    using (Stream zipStream = entry.Open(),
                           fileStream = fileInfo.Open(FileMode.Create, FileAccess.Write))
                    {
                        zipStream.CopyTo(fileStream);
                    }

                    fileInfo.LastWriteTimeUtc = entry.LastWriteTime.ToUniversalTime().DateTime;
                }
            }
        }
Exemple #3
0
        public static void Extract(this ZipArchive archive, string directoryName, ITracer tracer, bool doNotPreserveFileTime = false)
        {
            const int MaxExtractTraces = 5;

            var entries = archive.Entries;
            var total   = entries.Count;
            var traces  = 0;

            using (tracer.Step(string.Format("Extracting {0} entries to {1} directory", entries.Count, directoryName)))
            {
                foreach (ZipArchiveEntry entry in entries)
                {
                    string path = Path.Combine(directoryName, entry.FullName);
                    if (entry.Length == 0 && (path.EndsWith("/", StringComparison.Ordinal) || path.EndsWith("\\", StringComparison.Ordinal)))
                    {
                        // Extract directory
                        FileSystemHelpers.CreateDirectory(path);
                    }
                    else
                    {
                        FileInfoBase fileInfo = FileSystemHelpers.FileInfoFromFileName(path);

                        string message = null;
                        // tracing first/last N files
                        if (traces < MaxExtractTraces || traces >= total - MaxExtractTraces)
                        {
                            message = string.Format("Extracting to {0} ...", fileInfo.FullName);
                        }
                        else if (traces == MaxExtractTraces)
                        {
                            message = "Omitting extracting file traces ...";
                        }

                        ++traces;

                        using (!string.IsNullOrEmpty(message) ? tracer.Step(message) : null)
                        {
                            if (!fileInfo.Directory.Exists)
                            {
                                fileInfo.Directory.Create();
                            }

                            using (Stream zipStream = entry.Open(),
                                   fileStream = fileInfo.Open(FileMode.Create, FileAccess.Write))
                            {
                                zipStream.CopyTo(fileStream);
                            }

                            // this is to allow, the file time to always be newer than destination
                            // the outcome is always replacing the destination files.
                            // it is non-optimized but workaround NPM reset file time issue (https://github.com/projectkudu/kudu/issues/2917).
                            if (!doNotPreserveFileTime)
                            {
                                fileInfo.LastWriteTimeUtc = entry.LastWriteTime.ToUniversalTime().DateTime;
                            }
                        }
                    }
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Provides a common way for opening a file stream for exclusively deleting the file.
        /// </summary>
        private static Stream GetFileDeleteStream(FileInfoBase file)
        {
            ArgumentNullException.ThrowIfNull(file);

            // Open file exclusively for delete sharing only
            return(file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete));
        }
Exemple #5
0
        /// <summary>
        /// Provides a common way for opening a file stream for exclusively deleting the file.
        /// </summary>
        private static Stream GetFileDeleteStream(FileInfoBase file)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            // Open file exclusively for delete sharing only
            return(file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete));
        }
Exemple #6
0
 private IEnumerable <Row> ExtractDataSet(int tabIndex)
 {
     using (var excelReader = ExcelReaderFactory.CreateOpenXmlReader(_fileInfo.Open(FileMode.Open, FileAccess.Read)))
     {
         excelReader.IsFirstRowAsColumnNames = true;
         using (var table = excelReader.AsDataSet().Tables[tabIndex])
         {
             return(GetRows(table));
         }
     }
 }
Exemple #7
0
        public static void Save <T>(T obj, FileInfoBase file)
        {
            if (!file.Directory.Exists)
            {
                file.Directory.Create();
            }

            using (var stream = file.Open(FileMode.Create))
            {
                var binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(stream, obj);
            }
        }
Exemple #8
0
        /// <summary>
        /// Extracts source directories from the csproj file.
        /// The expected directory info list is the csproj's directory and all project references.
        /// </summary>
        /// <param name="csprojFile"></param>
        /// <returns></returns>
        private DirectoryInfoBase[] ExtractSourceDirectories(FileInfoBase csprojFile)
        {
            // Data validation
            Ensure.That(() => csprojFile).IsNotNull();
            Ensure.That(csprojFile.Exists, string.Format("Could not find '{0}' file", csprojFile)).IsTrue();

            // Initialize the extracted directories
            List <DirectoryInfoBase> extractedSourceDirectories = new List <DirectoryInfoBase>();

            // Add the csproj's directory
            DirectoryInfoBase projectDirectory = this.fileSystem.DirectoryInfo.FromDirectoryName(this.fileSystem.Path.GetDirectoryName(csprojFile.FullName));

            extractedSourceDirectories.Add(projectDirectory);

            // Load xml document
            XmlDocument xmlDocument = new XmlDocument();

            using (Stream stream = csprojFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                xmlDocument.Load(stream);
            }

            // Extract
            XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);

            xmlNamespaceManager.AddNamespace("msbuild", "http://schemas.microsoft.com/developer/msbuild/2003");
            XmlNodeList xmlNodes = xmlDocument.SelectNodes("//msbuild:ProjectReference", xmlNamespaceManager);

            for (int i = 0; i < xmlNodes.Count; ++i)
            {
                XmlNode xmlNode      = xmlNodes.Item(i);
                string  includeValue = xmlNode.Attributes["Include"].Value;
                string  combinedPath = this.fileSystem.Path.Combine(projectDirectory.FullName, includeValue);

                // The combinedPath can contains both forward and backslash path chunk.
                // In linux environment we can end up having "/..\" in the path which make the GetDirectoryName method bugging (returns empty).
                // For this reason we need to make sure that the combined path uses forward slashes
                combinedPath = combinedPath.Replace(@"\", "/");

                // Add the combined path
                extractedSourceDirectories.Add(this.fileSystem.DirectoryInfo.FromDirectoryName(this.fileSystem.Path.GetDirectoryName(this.fileSystem.Path.GetFullPath(combinedPath))));
            }

            // Return the extracted directories
            return(extractedSourceDirectories.ToArray());
        }
Exemple #9
0
 public Stream OpenWrite()
 {
     return(_file.Open(FileMode.Create, FileAccess.Write));
 }
        public static IDictionary <string, string> Extract(this ZipArchive archive, string directoryName, bool preserveSymlinks = false)
        {
            IDictionary <string, string> symLinks = new Dictionary <string, string>();
            bool isSymLink = false;

            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                string path = Path.Combine(directoryName, entry.FullName);
                if (entry.Length == 0 && (path.EndsWith("/", StringComparison.Ordinal) || path.EndsWith("\\", StringComparison.Ordinal)))
                {
                    // Extract directory
                    FileSystemHelpers.CreateDirectory(path);
                }
                else
                {
                    FileInfoBase fileInfo = FileSystemHelpers.FileInfoFromFileName(path);

                    if (!fileInfo.Directory.Exists)
                    {
                        fileInfo.Directory.Create();
                    }
                    using (Stream zipStream = entry.Open(),
                           fileStream = fileInfo.Open(FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                    {
                        zipStream.CopyTo(fileStream);
                    }

                    isSymLink = false;
                    string originalFileName = string.Empty;

                    if (!OSDetector.IsOnWindows())
                    {
                        try
                        {
                            using (Stream fs = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            {
                                byte[] buffer = new byte[4];
                                fs.Read(buffer, 0, buffer.Length);
                                fs.Close();

                                var str = System.Text.Encoding.Default.GetString(buffer);
                                if (preserveSymlinks && str.StartsWith("../"))
                                {
                                    using (StreamReader reader = fileInfo.OpenText())
                                    {
                                        symLinks[entry.FullName] = reader.ReadToEnd();
                                    }
                                    isSymLink = true;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Could not identify symlinks in zip file : " + ex.ToString());
                        }
                    }

                    try
                    {
                        fileInfo.LastWriteTimeUtc = entry.LastWriteTime.ToUniversalTime().DateTime;
                    }
                    catch (Exception)
                    {
                        //best effort
                    }

                    if (isSymLink)
                    {
                        fileInfo.Delete();
                    }
                }
            }
            return(symLinks);
        }
        public static void Extract(this ZipArchive archive, string directoryName)
        {
            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                string path = Path.Combine(directoryName, entry.FullName);
                if (entry.Length == 0 && (path.EndsWith("/", StringComparison.Ordinal) || path.EndsWith("\\", StringComparison.Ordinal)))
                {
                    // Extract directory
                    FileSystemHelpers.CreateDirectory(path);
                }
                else
                {
                    FileInfoBase fileInfo = FileSystemHelpers.FileInfoFromFileName(path);

                    if (!fileInfo.Directory.Exists)
                    {
                        fileInfo.Directory.Create();
                    }

                    using (Stream zipStream = entry.Open(),
                           fileStream = fileInfo.Open(FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                    {
                        zipStream.CopyTo(fileStream);
                    }

                    bool   createSymLink    = false;
                    string originalFileName = string.Empty;
                    if (!OSDetector.IsOnWindows())
                    {
                        try
                        {
                            using (Stream fs = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            {
                                byte[] buffer = new byte[10];
                                fs.Read(buffer, 0, buffer.Length);
                                fs.Close();

                                var str = System.Text.Encoding.Default.GetString(buffer);
                                if (str.StartsWith("../"))
                                {
                                    string fullPath = Path.GetFullPath(str);
                                    if (fullPath.StartsWith(directoryName))
                                    {
                                        createSymLink    = true;
                                        originalFileName = fullPath;
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Could not identify symlinks in zip file : " + ex.ToString());
                        }
                    }

                    fileInfo.LastWriteTimeUtc = entry.LastWriteTime.ToUniversalTime().DateTime;

                    if (createSymLink)
                    {
                        try
                        {
                            fileInfo.Delete();

                            Mono.Unix.UnixFileInfo unixFileInfo = new Mono.Unix.UnixFileInfo(originalFileName);
                            unixFileInfo.CreateSymbolicLink(path);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Could not create symlinks : " + ex.ToString());
                        }
                    }
                }
            }
        }