Exemplo n.º 1
0
		public static void AddDirectory(this ZipArchive archive, string sourceDir)
		{
			DirectoryInfo directoryInfo = new DirectoryInfo(sourceDir);
			sourceDir = directoryInfo.FullName;

			foreach (FileSystemInfo entry in directoryInfo.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
			{
				string relativePath = entry.FullName.Substring(sourceDir.Length, entry.FullName.Length - sourceDir.Length);
				relativePath = relativePath.TrimStart(new char[]
				{
					Path.DirectorySeparatorChar,
					Path.AltDirectorySeparatorChar
				});

				if (entry is FileInfo)
				{
					archive.AddFile(entry.FullName, relativePath);
				}
				else
				{
					DirectoryInfo subDirInfo = entry as DirectoryInfo;
					if (subDirInfo != null && !subDirInfo.EnumerateFileSystemInfos().Any())
					{
						archive.CreateEntry(relativePath + Path.DirectorySeparatorChar);
					}
				}
			}
		}
Exemplo n.º 2
0
 internal static void AddFileWithCheck(this IFileSystem fileSystem, string path, Func<Stream> streamFactory)
 {
     using (Stream stream = streamFactory())
     {
         fileSystem.AddFile(path, stream);
     }
 }
Exemplo n.º 3
0
 internal static void AddFile(this IFileSystem fileSystem, string path, Action<Stream> write)
 {
     using (var stream = new MemoryStream()) {
         write(stream);
         stream.Seek(0, SeekOrigin.Begin);
         fileSystem.AddFile(path, stream);
     }
 }
Exemplo n.º 4
0
        public static MockFileSystem WithFiles(this MockFileSystem mockFileSystem, params string[] paths)
        {
            foreach (var path in paths)
            {
                mockFileSystem.AddFile(mockFileSystem.Path.Combine(mockFileSystem.Directory.GetCurrentDirectory(), path), new MockFileData(""));
            }

            return mockFileSystem;
        }
Exemplo n.º 5
0
            public static System.Tuple<Bam.Core.Module, Bam.Core.Module> GenerateSource(
                this C.CObjectFileCollection collection)
            {
                // generate source file
                var generatedSourceFile = Bam.Core.Module.Create<GeneratedSourceModule>(collection);

                // compile the generated source file
                var objFile = collection.AddFile(generatedSourceFile);

                // return both generated source, and the compiled object file
                return new System.Tuple<Bam.Core.Module, Bam.Core.Module>(generatedSourceFile, objFile);
            }
Exemplo n.º 6
0
 internal static void AddFileWithCheck(this IFileSystem fileSystem, string path, Func<Stream> streamFactory)
 {
     // Don't overwrite file if it exists if force wasn't set to true
     if (fileSystem.FileExists(path)) {
         fileSystem.Logger.Log(MessageLevel.Warning, NuGetResources.Warning_FileAlreadyExists, path);
     }
     else {
         using (Stream stream = streamFactory()) {
             fileSystem.AddFile(path, stream);
         }
     }
 }
Exemplo n.º 7
0
 /// <summary>
 /// Добавляет директорию в указанную коллекцию кассеты. Возвращает добавленные в базу данных элементы
 /// </summary>
 /// <param name="dir"></param>
 /// <param name="collectionId"></param>
 /// <returns>Возвращает добавленные в базу данных элементы</returns>
 public static IEnumerable<XElement> AddDirectory(this Cassette cassette, DirectoryInfo dir, string collectionId)
 {
     List<XElement> addedElements = new List<XElement>();
     var dname = dir.FullName;
     var shortname = dir.Name;
     // TODO: Надо учесть русские имена и с пробелами
     var newcoll_id = "collection_" + cassette.Name + "_" + dname;
     // Поищу, нет ли такой коллекции в базе данных
     var collection_found =
         cassette.db.Elements(ONames.TagCollection)
             .FirstOrDefault((XElement e) =>
             {
                 var xabout = e.Attribute(ONames.rdfabout);
                 return (xabout != null && xabout.Value == newcoll_id);
             });
     if(collection_found != null) { }
     else
     {
         // Создам коллекцию
         XElement coll =
             new XElement(ONames.TagCollection,
                 new XAttribute(ONames.rdfabout, newcoll_id),
                 new XElement(ONames.TagName, shortname));
         cassette.db.Add(coll);
         addedElements.Add(coll);
         // Присоединим коллекцию к вышестоящей
         XElement collmem =
             new XElement(ONames.TagCollectionmember,
                 new XAttribute(ONames.rdfabout, "cm_" + newcoll_id),
                 new XElement(ONames.TagCollectionitem,
                     new XAttribute(ONames.rdfresource, newcoll_id)),
                 new XElement(ONames.TagIncollection,
                     new XAttribute(ONames.rdfresource, collectionId)));
         cassette.db.Add(collmem);
         addedElements.Add(collmem);
         cassette.Changed = true;
     }
     // Обработаем файлы и директории
     foreach(var f in dir.GetFiles())
     {
         if(f.Name == "Thumbs.db") { }
         else addedElements.AddRange(cassette.AddFile(f, newcoll_id));
     }
     foreach(var d in dir.GetDirectories())
         addedElements.AddRange(cassette.AddDirectory(d, newcoll_id));
     return addedElements;
 }
Exemplo n.º 8
0
        public static System.Tuple<Bam.Core.Module, Bam.Core.Module> Rcc(
            this C.Cxx.ObjectFileCollection collection,
            QRCFile qrcFile)
        {
            // rcc the .qrc file to generate the source file
            var rccSourceFile = Bam.Core.Module.Create<RccGeneratedSource>(collection);

            // compile the generated source file
            var objFile = collection.AddFile(rccSourceFile);

            // set the source file AFTER the source has been chained into the object file
            // so that the encapsulating module can be determined
            rccSourceFile.SourceHeader = qrcFile;

            // return both rcc'd source, and the compiled object file
            return new System.Tuple<Bam.Core.Module, Bam.Core.Module>(rccSourceFile, objFile);
        }
Exemplo n.º 9
0
        public static System.Tuple<Bam.Core.Module, Bam.Core.Module> MocHeader(
            this C.Cxx.ObjectFileCollection collection,
            C.HeaderFile header)
        {
            // moc the header file to generate the source file
            var mocSourceFile = Bam.Core.Module.Create<MocGeneratedSource>(collection);

            // compile the generated source file
            var objFile = collection.AddFile(mocSourceFile);

            // set the source header AFTER the source has been chained into the object file
            // so that the encapsulating module can be determined
            mocSourceFile.SourceHeader = header;

            // return both moc'd source, and the compiled object file
            return new System.Tuple<Bam.Core.Module, Bam.Core.Module>(mocSourceFile, objFile);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates a .refresh file in bin directory of the IProjectSystem that points to the assembly being installed. 
        /// This works around issues in DTE's AddReference method when dealing with GACed binaries.
        /// </summary>
        /// <param name="projectSystem">The project system the assembly is being referenced by.</param>
        /// <param name="assemblyPath">The relative path to the assembly being added</param>
        internal static void CreateRefreshFile(this IProjectSystem projectSystem, string assemblyPath)
        {
            string referenceName = Path.GetFileName(assemblyPath);
            string refreshFilePath = Path.Combine("bin", referenceName + ".refresh");
            if (!projectSystem.FileExists(refreshFilePath))
            {
                string projectPath = PathUtility.EnsureTrailingSlash(projectSystem.Root);
                string relativeAssemblyPath = PathUtility.GetRelativePath(projectPath, assemblyPath);

                try
                {
                    using (var stream = relativeAssemblyPath.AsStream())
                    {
                        projectSystem.AddFile(refreshFilePath, stream);
                    }
                }
                catch (UnauthorizedAccessException exception)
                {
                    // log IO permission error
                    ExceptionHelper.WriteToActivityLog(exception);
                }
            }
        }
Exemplo n.º 11
0
        public static void AddDirectory(this ZipArchive zipArchive, DirectoryInfoBase directory, string directoryNameInArchive)
        {
            bool any = false;
            foreach (var info in directory.GetFileSystemInfos())
            {
                any = true;
                var subDirectoryInfo = info as DirectoryInfoBase;
                if (subDirectoryInfo != null)
                {
                    string childName = Path.Combine(directoryNameInArchive, subDirectoryInfo.Name);
                    zipArchive.AddDirectory(subDirectoryInfo, childName);
                }
                else
                {
                    zipArchive.AddFile((FileInfoBase)info, directoryNameInArchive);
                }
            }

            if (!any)
            {
                // If the directory did not have any files or folders, add a entry for it
                zipArchive.CreateEntry(EnsureTrailingSlash(directoryNameInArchive));
            }
        }
Exemplo n.º 12
0
 internal static void AddFileWithCheck(this IFileSystem fileSystem, string path, Action<Stream> write)
 {
     if (fileSystem.FileExists(path))
     {
         fileSystem.Logger.Log(MessageLevel.Warning, NuGetResources.Warning_FileAlreadyExists, path);
     }
     else
     {
         fileSystem.AddFile(path, write);
     }
 }
Exemplo n.º 13
0
 internal static void AddFileWithCheck(this IFileSystem fileSystem, string path, Action<Stream> write)
 {
     fileSystem.AddFile(path, write);
 }
 /// <summary>
 ///   Adds a File to a Zip file archive.
 /// </summary>
 /// <remarks>
 ///
 /// <para>
 ///   This call collects metadata for the named file in the filesystem,
 ///   including the file attributes and the timestamp, and inserts that metadata
 ///   into the resulting ZipEntry.  Only when the application calls Save() on
 ///   the <c>ZipFile</c>, does DotNetZip read the file from the filesystem and
 ///   then write the content to the zip file archive.
 /// </para>
 ///
 /// <para>
 ///   This method will throw an exception if an entry with the same name already
 ///   exists in the <c>ZipFile</c>.
 /// </para>
 ///
 /// <para>
 ///   For <c>ZipFile</c> properties including <see cref="Encryption"/>, <see
 ///   cref="Password"/>, <see cref="SetCompression"/>, <see
 ///   cref="ProvisionalAlternateEncoding"/>, <see cref="ExtractExistingFile"/>,
 ///   <see cref="ZipErrorAction"/>, and <see cref="CompressionLevel"/>, their
 ///   respective values at the time of this call will be applied to the
 ///   <c>ZipEntry</c> added.
 /// </para>
 ///
 /// </remarks>
 ///
 /// <example>
 /// <para>
 ///   In this example, three files are added to a Zip archive. The ReadMe.txt
 ///   file will be placed in the root of the archive. The .png file will be
 ///   placed in a folder within the zip called photos\personal.  The pdf file
 ///   will be included into a folder within the zip called Desktop.
 /// </para>
 /// <code>
 ///    try
 ///    {
 ///      using (ZipFile zip = new ZipFile())
 ///      {
 ///        zip.AddFile("c:\\photos\\personal\\7440-N49th.png");
 ///        zip.AddFile("c:\\Desktop\\2008-Regional-Sales-Report.pdf");
 ///        zip.AddFile("ReadMe.txt");
 ///
 ///        zip.Save("Package.zip");
 ///      }
 ///    }
 ///    catch (System.Exception ex1)
 ///    {
 ///      System.Console.Error.WriteLine("exception: " + ex1);
 ///    }
 /// </code>
 ///
 /// <code lang="VB">
 ///  Try
 ///       Using zip As ZipFile = New ZipFile
 ///           zip.AddFile("c:\photos\personal\7440-N49th.png")
 ///           zip.AddFile("c:\Desktop\2008-Regional-Sales-Report.pdf")
 ///           zip.AddFile("ReadMe.txt")
 ///           zip.Save("Package.zip")
 ///       End Using
 ///   Catch ex1 As Exception
 ///       Console.Error.WriteLine("exception: {0}", ex1.ToString)
 ///   End Try
 /// </code>
 /// </example>
 ///
 /// <overloads>This method has two overloads.</overloads>
 ///
 /// <seealso cref="Ionic.Zip.ZipFile.AddItem(string)"/>
 /// <seealso cref="Ionic.Zip.ZipFile.AddDirectory(string)"/>
 /// <seealso cref="Ionic.Zip.ZipFile.UpdateFile(string)"/>
 ///
 /// <param name="fileName">
 ///   The name of the file to add. It should refer to a file in the filesystem.
 ///   The name of the file may be a relative path or a fully-qualified path.
 /// </param>
 /// <returns>The <c>ZipEntry</c> corresponding to the File added.</returns>
 public static ZipEntry AddFile(this ZipFile zipFile, string fileName)
 {
     return zipFile.AddFile(fileName, null);
 }
Exemplo n.º 15
0
		public static DBFile AddFile (this DBWork me, DB db, string path, string filename, bool hidden, string compressed_mime)
		{
			DBFile result = db.Upload (path, Path.GetExtension (filename), hidden, compressed_mime);
			me.AddFile (db, result, filename, hidden);
			return result;
		}
Exemplo n.º 16
0
 public static MockFileSystem WithEmptyGitIgnore(this MockFileSystem mockFileSystem)
 {
     mockFileSystem.AddFile(@"C:\.gitignore", new MockFileData(""));
     return mockFileSystem;
 }
        /// <summary>
        ///   Adds a set of files to the <c>ZipFile</c>, using the specified directory
        ///   path in the archive, and preserving the full directory structure in the
        ///   filenames.
        /// </summary>
        ///
        /// <remarks>
        ///
        /// <para>
        ///   Think of the <paramref name="directoryPathInArchive"/> as a "root" or
        ///   base directory used in the archive for the files that get added.  when
        ///   <paramref name="preserveDirHierarchy"/> is true, the hierarchy of files
        ///   found in the filesystem will be placed, with the hierarchy intact,
        ///   starting at that root in the archive. When <c>preserveDirHierarchy</c>
        ///   is false, the path hierarchy of files is flattned, and the flattened
        ///   set of files gets placed in the root within the archive as specified in
        ///   <c>directoryPathInArchive</c>.
        /// </para>
        ///
        /// <para>
        ///   For <c>ZipFile</c> properties including <see cref="Encryption"/>, <see
        ///   cref="Password"/>, <see cref="SetCompression"/>, <see
        ///   cref="ProvisionalAlternateEncoding"/>, <see cref="ExtractExistingFile"/>,
        ///   <see cref="ZipErrorAction"/>, and <see cref="CompressionLevel"/>, their
        ///   respective values at the time of this call will be applied to each
        ///   ZipEntry added.
        /// </para>
        ///
        /// </remarks>
        ///
        /// <param name="fileNames">
        ///   The names of the files to add. Each string should refer to a file in the
        ///   filesystem.  The name of the file may be a relative path or a
        ///   fully-qualified path.
        /// </param>
        ///
        /// <param name="directoryPathInArchive">
        ///   Specifies a directory path to use as a prefix for each entry name.
        ///   This path may, or may not, correspond to a real directory in the current
        ///   filesystem.  If the files within the zip are later extracted, this is the
        ///   path used for the extracted file.  Passing <c>null</c> (<c>Nothing</c> in
        ///   VB) will use the path on each of the <c>fileNames</c>, if any.  Passing
        ///   the empty string ("") will insert the item at the root path within the
        ///   archive.
        /// </param>
        ///
        /// <param name="preserveDirHierarchy">
        ///   whether the entries in the zip archive will reflect the directory
        ///   hierarchy that is present in the various filenames.  For example, if
        ///   <paramref name="fileNames"/> includes two paths,
        ///   \Animalia\Chordata\Mammalia\Info.txt and
        ///   \Plantae\Magnoliophyta\Dicotyledon\Info.txt, then calling this method
        ///   with <paramref name="preserveDirHierarchy"/> = <c>false</c> will
        ///   result in an exception because of a duplicate entry name, while
        ///   calling this method with <paramref name="preserveDirHierarchy"/> =
        ///   <c>true</c> will result in the full direcory paths being included in
        ///   the entries added to the ZipFile.
        /// </param>
        /// <seealso cref="Ionic.Zip.ZipFile.AddSelectedFiles(String, String)" />
        public static void AddFiles(this ZipFile zipFile, System.Collections.Generic.IEnumerable<String> fileNames, String directoryPathInArchive, bool preserveDirHierarchy)
        {
            if (fileNames == null)
                throw new ArgumentNullException("fileNames");

            zipFile.SetAddOperationCanceled(false);
            zipFile.SetInAddAll(true);
            try
            {
            zipFile.OnAddStarted();
            if (preserveDirHierarchy)
            {
                foreach (var f in fileNames)
                {
                    if (zipFile.IsAddOperationCanceled()) break;
                    if (directoryPathInArchive != null)
                    {
                        //string s = SharedUtilities.NormalizePath(Path.Combine(directoryPathInArchive, Path.GetDirectoryName(f)));
                        string s = ZipEntryInternal.NormalizePath(Path.Combine(directoryPathInArchive, Path.GetDirectoryName(f)));
                        zipFile.AddFile(f, s);
                    }
                    else
                        zipFile.AddFile(f, null);
                }
            }
            else
            {
                foreach (var f in fileNames)
                {
                    if (zipFile.IsAddOperationCanceled()) break;
                    zipFile.AddFile(f, directoryPathInArchive);
                }
            }
            if (!zipFile.IsAddOperationCanceled())
                zipFile.OnAddCompleted();
            }
            finally
            {
                zipFile.SetInAddAll(false);
            }
        }
        /// <summary>
        ///   Adds an item, either a file or a directory, to a zip file archive,
        ///   explicitly specifying the directory path to be used in the archive.
        /// </summary>
        ///
        /// <remarks>
        /// <para>
        ///   If adding a directory, the add is recursive on all files and
        ///   subdirectories contained within it.
        /// </para>
        /// <para>
        ///   The name of the item may be a relative path or a fully-qualified path.
        ///   The item added by this call to the <c>ZipFile</c> is not read from the
        ///   disk nor written to the zip file archive until the application calls
        ///   Save() on the <c>ZipFile</c>.
        /// </para>
        ///
        /// <para>
        ///   This version of the method allows the caller to explicitly specify the
        ///   directory path to be used in the archive, which would override the
        ///   "natural" path of the filesystem file.
        /// </para>
        ///
        /// <para>
        ///   Encryption will be used on the file data if the <c>Password</c> has
        ///   been set on the <c>ZipFile</c> object, prior to calling this method.
        /// </para>
        ///
        /// <para>
        ///   For <c>ZipFile</c> properties including <see cref="Encryption"/>, <see
        ///   cref="Password"/>, <see cref="SetCompression"/>, <see
        ///   cref="ProvisionalAlternateEncoding"/>, <see cref="ExtractExistingFile"/>,
        ///   <see cref="ZipErrorAction"/>, and <see cref="CompressionLevel"/>, their
        ///   respective values at the time of this call will be applied to the
        ///   <c>ZipEntry</c> added.
        /// </para>
        ///
        /// </remarks>
        ///
        /// <exception cref="System.IO.FileNotFoundException">
        ///   Thrown if the file or directory passed in does not exist.
        /// </exception>
        ///
        /// <param name="fileOrDirectoryName">the name of the file or directory to add.
        /// </param>
        ///
        /// <param name="directoryPathInArchive">
        ///   The name of the directory path to use within the zip archive.  This path
        ///   need not refer to an extant directory in the current filesystem.  If the
        ///   files within the zip are later extracted, this is the path used for the
        ///   extracted file.  Passing <c>null</c> (<c>Nothing</c> in VB) will use the
        ///   path on the fileOrDirectoryName.  Passing the empty string ("") will
        ///   insert the item at the root path within the archive.
        /// </param>
        ///
        /// <seealso cref="Ionic.Zip.ZipFile.AddFile(string, string)"/>
        /// <seealso cref="Ionic.Zip.ZipFile.AddDirectory(string, string)"/>
        /// <seealso cref="Ionic.Zip.ZipFile.UpdateItem(string, string)"/>
        ///
        /// <example>
        ///   This example shows how to zip up a set of files into a flat hierarchy,
        ///   regardless of where in the filesystem the files originated. The resulting
        ///   zip archive will contain a toplevel directory named "flat", which itself
        ///   will contain files Readme.txt, MyProposal.docx, and Image1.jpg.  A
        ///   subdirectory under "flat" called SupportFiles will contain all the files
        ///   in the "c:\SupportFiles" directory on disk.
        ///
        /// <code>
        /// String[] itemnames= {
        ///   "c:\\fixedContent\\Readme.txt",
        ///   "MyProposal.docx",
        ///   "c:\\SupportFiles",  // a directory
        ///   "images\\Image1.jpg"
        /// };
        ///
        /// try
        /// {
        ///   using (ZipFile zip = new ZipFile())
        ///   {
        ///     for (int i = 1; i &lt; itemnames.Length; i++)
        ///     {
        ///       // will add Files or Dirs, recurses and flattens subdirectories
        ///       zip.AddItem(itemnames[i],"flat");
        ///     }
        ///     zip.Save(ZipToCreate);
        ///   }
        /// }
        /// catch (System.Exception ex1)
        /// {
        ///   System.Console.Error.WriteLine("exception: {0}", ex1);
        /// }
        /// </code>
        ///
        /// <code lang="VB">
        ///   Dim itemnames As String() = _
        ///     New String() { "c:\fixedContent\Readme.txt", _
        ///                    "MyProposal.docx", _
        ///                    "SupportFiles", _
        ///                    "images\Image1.jpg" }
        ///   Try
        ///       Using zip As New ZipFile
        ///           Dim i As Integer
        ///           For i = 1 To itemnames.Length - 1
        ///               ' will add Files or Dirs, recursing and flattening subdirectories.
        ///               zip.AddItem(itemnames(i), "flat")
        ///           Next i
        ///           zip.Save(ZipToCreate)
        ///       End Using
        ///   Catch ex1 As Exception
        ///       Console.Error.WriteLine("exception: {0}", ex1.ToString())
        ///   End Try
        /// </code>
        /// </example>
        /// <returns>The <c>ZipEntry</c> added.</returns>
        public static ZipEntry AddItem(this ZipFile zipFile, String fileOrDirectoryName, String directoryPathInArchive)
        {
            string fullPath = GetFullPath(fileOrDirectoryName);

            if (FileSystem.Current.GetFileFromPathAsync(fullPath).ExecuteSync() != null)
                return zipFile.AddFile(fileOrDirectoryName, directoryPathInArchive);

            if (FileSystem.Current.GetFolderFromPathAsync(fullPath).ExecuteSync() != null)
                return zipFile.AddDirectory(fileOrDirectoryName, directoryPathInArchive);

            throw new FileNotFoundException(String.Format("That file or directory ({0}) does not exist!",
                                                          fileOrDirectoryName));
        }
 /// <summary>
 ///   Adds or Updates a File in a Zip file archive.
 /// </summary>
 ///
 /// <remarks>
 /// <para>
 ///   This method adds a file to a zip archive, or, if the file already exists
 ///   in the zip archive, this method Updates the content of that given filename
 ///   in the zip archive.
 /// </para>
 ///
 /// <para>
 ///   This version of the method allows the caller to explicitly specify the
 ///   directory path to be used in the archive.  The entry to be added or
 ///   updated is found by using the specified directory path, combined with the
 ///   basename of the specified filename.
 /// </para>
 ///
 /// <para>
 ///   Upon success, there is no way for the application to learn if the file was
 ///   added versus updated.
 /// </para>
 ///
 /// <para>
 ///   For <c>ZipFile</c> properties including <see cref="Encryption"/>, <see
 ///   cref="Password"/>, <see cref="SetCompression"/>, <see
 ///   cref="ProvisionalAlternateEncoding"/>, <see cref="ExtractExistingFile"/>,
 ///   <see cref="ZipErrorAction"/>, and <see cref="CompressionLevel"/>, their
 ///   respective values at the time of this call will be applied to the
 ///   <c>ZipEntry</c> added.
 /// </para>
 /// </remarks>
 ///
 /// <seealso cref="Ionic.Zip.ZipFile.AddFile(string,string)"/>
 /// <seealso cref="Ionic.Zip.ZipFile.UpdateDirectory(string,string)"/>
 /// <seealso cref="Ionic.Zip.ZipFile.UpdateItem(string,string)"/>
 ///
 /// <param name="fileName">
 ///   The name of the file to add or update. It should refer to a file in the
 ///   filesystem.  The name of the file may be a relative path or a
 ///   fully-qualified path.
 /// </param>
 ///
 /// <param name="directoryPathInArchive">
 ///   Specifies a directory path to use to override any path in the
 ///   <c>fileName</c>.  This path may, or may not, correspond to a real
 ///   directory in the current filesystem.  If the files within the zip are
 ///   later extracted, this is the path used for the extracted file.  Passing
 ///   <c>null</c> (<c>Nothing</c> in VB) will use the path on the
 ///   <c>fileName</c>, if any.  Passing the empty string ("") will insert the
 ///   item at the root path within the archive.
 /// </param>
 ///
 /// <returns>
 ///   The <c>ZipEntry</c> corresponding to the File that was added or updated.
 /// </returns>
 public static ZipEntry UpdateFile(this ZipFile zipFile, string fileName, String directoryPathInArchive)
 {
     // ideally this would all be transactional!
     var key = ZipEntryInternal.NameInArchive(fileName, directoryPathInArchive);
     if (zipFile[key] != null)
         zipFile.RemoveEntry(key);
     return zipFile.AddFile(fileName, directoryPathInArchive);
 }
Exemplo n.º 20
0
 public static IEnumerable<XElement> AddNewRdf(this Cassette cassette, string owner)
 {
     string dbid = cassette.Name + "_" + owner + "_" + DateTime.Now.Ticks.ToString();
     XElement emptyRdfDoc = Cassette.RDFdb(dbid,
         new XAttribute(ONames.AttOwner, owner),
         new XAttribute(ONames.AttPrefix, dbid + "_"),
         new XAttribute(ONames.AttCounter, "1001"));
     string filepath = cassette.Dir.FullName + "/" + dbid + ".fog";
     emptyRdfDoc.Save(filepath);
     var seq = cassette.AddFile(new FileInfo(filepath), cassette.CollectionId).ToList();
     // Надо добавить владельца в iisstore документа и хорошо бы проставить uri (это надо делать в файле)
     XElement rdfdoc = seq.First(xe => xe.Name == ONames.TagDocument);
     XElement iisstore = rdfdoc.Element(ONames.TagIisstore);
     iisstore.Add(new XAttribute(ONames.AttOwner, owner));
     File.Delete(filepath);
     return seq;
 }
Exemplo n.º 21
0
 /// <summary>
 /// Adds a group of files to this load procedure
 /// </summary>
 /// <param name="proc"></param>
 /// <param name="files"></param>
 public static void AddFiles(this IBaseLoadProcedure proc, IEnumerable<string> files)
 {
     Check.NotNull(proc, "proc"); //NOXLATE
     Check.NotNull(files, "files"); //NOXLATE
     foreach (var f in files)
     {
         proc.AddFile(f);
     }
 }
Exemplo n.º 22
0
		public static ZipArchiveEntry AddFile(this ZipArchive archive, string sourceFile)
		{
			return archive.AddFile(sourceFile, Path.GetFileName(sourceFile));
		}
Exemplo n.º 23
0
 public static MockFileSystem WithGitIgnoreContaining(this MockFileSystem mockFileSystem, string contents)
 {
     mockFileSystem.AddFile(@"C:\.gitignore", new MockFileData(contents));
     return mockFileSystem;
 }
Exemplo n.º 24
0
 public static void CopyFile(this IFileSystem fs, string path, string newPath)
 {
     fs.AddFile(newPath, fs.OpenFile(path));
 }
Exemplo n.º 25
0
 public static MockFileSystem WithFile(this MockFileSystem mockFileSystem, string path)
 {
     mockFileSystem.AddFile(mockFileSystem.Path.Combine(mockFileSystem.Directory.GetCurrentDirectory(), path), new MockFileData(""));
     return mockFileSystem;
 }
Exemplo n.º 26
0
 public static void AddFile(this ZipArchive zipArchive, string filePath, string directoryNameInArchive = "")
 {
     var fileInfo = new FileInfoWrapper(new FileInfo(filePath));
     zipArchive.AddFile(fileInfo, directoryNameInArchive);
 }
        internal static ZipEntry AddOrUpdateDirectoryImpl(this ZipFile zipFile, string directoryName, string rootDirectoryPathInArchive, AddOrUpdateAction action, bool recurse, int level)
        {
            string fullPath = GetFullPath(directoryName);

            if (zipFile.StatusMessageTextWriter != null)
                zipFile.StatusMessageTextWriter.WriteLine("{0} {1}...",
                                                  (action == AddOrUpdateAction.AddOnly) ? "adding" : "Adding or updating",
                                                  directoryName);

            if (level == 0)
            {
                zipFile.SetAddOperationCanceled(false);
                zipFile.OnAddStarted();
            }

            // workitem 13371
            if (zipFile.IsAddOperationCanceled())
                return null;

            string dirForEntries = rootDirectoryPathInArchive;
            ZipEntry baseDir = null;

            if (level > 0)
            {
                int f = directoryName.Length;
                for (int i = level; i > 0; i--)
                    f = directoryName.LastIndexOfAny("/\\".ToCharArray(), f - 1, f - 1);

                dirForEntries = directoryName.Substring(f + 1);
                dirForEntries = Path.Combine(rootDirectoryPathInArchive, dirForEntries);
            }

            // if not top level, or if the root is non-empty, then explicitly add the directory
            if (level > 0 || rootDirectoryPathInArchive != "")
            {
                // add the directory only if it does not exist.
                // It's not an error if it already exists.
                dirForEntries = ZipEntryInternal.NameInArchive(dirForEntries) + '/';
                if (!zipFile.EntryFileNames.Contains(dirForEntries))
                {
                    baseDir = zipFile.AddDirectoryByName(dirForEntries);
                }
            }

            if (!zipFile.IsAddOperationCanceled())
            {
                IFile fileCheck = FileSystem.Current.GetFileFromPathAsync(fullPath).ExecuteSync();
                if (fileCheck != null)
                {
                    throw new IOException(string.Format("That path ({0}) is a file, not a directory!", directoryName));
                }
                IFolder folder = FileSystem.Current.GetFolderFromPathAsync(fullPath).ExecuteSync();
                if (folder == null)
                {
                    throw new FileNotFoundException(string.Format("That folder ({0}) does not exist!", directoryName));
                }
                IList<IFile> files = folder.GetFilesAsync().ExecuteSync();

                if (recurse)
                {
                    // add the files:
                    foreach (IFile file in files)
                    {
                        if (zipFile.IsAddOperationCanceled()) break;
                        if (action == AddOrUpdateAction.AddOnly)
                            zipFile.AddFile(file.Path, dirForEntries);
                        else
                            zipFile.UpdateFile(file.Path, dirForEntries);
                    }

                    if (!zipFile.IsAddOperationCanceled())
                    {
                        // add the subdirectories:
                        IList<IFolder> dirs = folder.GetFoldersAsync().ExecuteSync();
                        foreach (IFolder dir in dirs)
                        {
                                zipFile.AddOrUpdateDirectoryImpl(dir.Path, rootDirectoryPathInArchive, action, recurse, level + 1);
                        }

                    }
                }
            }

            if (level == 0)
                zipFile.OnAddCompleted();

            return baseDir;
        }