Contains function doesn't find specific files in sub directories - c#

I created a string array that utilizes the Directory.GetFiles function which populates the array with .cs file extensions from all sub directories in my project. This is fine, however, I was trying to write these files to a text document while excluding specific files from the array such as "AssemblyInfo.cs" and "TemporaryGeneratedFiles_xxx.cs" using the contains method to filter files with these names. For the most part, the large majority of these files were not written to the text document, however, there are a few cases where these files manage to show up within the text document.
I've tried using a foreach statement instead of a for loop. I've tried playing around with the str.flush(), str.close(), directoryNames.Dispose(), and directoryNames.Close() by putting them in different spots of the for loop. I tried nesting the if statements instead of using the && operator. The || operator doesn't work in this situation. I've tried using the entire file name and only bits and pieces of the file name and none of this seems to work. At one point I did manage to remove all file that had "Temporary" in it but the "AssemblyInfo.cs" files still remain. I even made a method to completely remove anything with the word temporary or assembly in its file name but that also failed.
FileStream directoryNames = new FileStream(dirListPath, FileMode.OpenOrCreate);
StreamWriter str = new StreamWriter(directoryNames);
string[] allFiles = Directory.GetFiles(dirPath, "*.cs", SearchOption.AllDirectories);
for (int i = 0; i < allFiles.Length; i++)
{
if ((!allFiles[i].Contains("Temporary")) && (!allFiles[i].Contains("Assembly")))
{
str.Write(allFiles[i] + Environment.NewLine);
}
}
str.Flush();
str.Close();
directoryNames.Dispose();
directoryNames.Close();
No error messages occur but as stated above unexpected files pop up where they shouldn't be. Any help would be greatly appreciated.

Thanks to everyone who posted.
After some testing mjwillis was correct. Instead of overwriting the contents in the text file it kept writing to the top of the file and adding on to the contents that were written previously. Fixed it by adding
using (FileStream clearTextDocument = File.Create(dirListPath)) { }
Before the FileStream DirectoryNames line. Feel free to post another way to clear a text document if it's more attractive than this.

As #steve suggested you code ignores case sensitivity.
Try this one.
var allFiles = Directory.EnumerateFiles(dirPath, "*.cs", SearchOption.AllDirectories)
.Where(file => file.IndexOf("Temporary", StringComparison.InvariantCultureIgnoreCase) < 0
&& file.IndexOf("Assembly", StringComparison.InvariantCultureIgnoreCase) < 0);
File.WriteAllLines(dirListPath, allFiles);
PS: This code makes many changes to your code, but in essence they are same.

Related

C#: Programmatically create a split zip file

I want to create a zip file from a folder that it around 1.5GB, and have that zip file be split into chunks of 100MB. I've found quite a few threads on this, but nothing has quite worked out for me.
First I tried System.IO.Compression, but found that it doesn't support splitting the zip files (please correct me if I'm wrong!).
Next I tried Ionic.zip, which looked super easy, but every set of files I create is corrupted in some way (for example, the following code that uses the fonts directory as a test directory creates a set of files that I can't then open or unzip as an archive with either winzip or winrar):
using (var zipFile = new Ionic.Zip.ZipFile(Encoding.UTF8))
{
zipFile.AddDirectory("c:\\windows\\fonts", directoryPathInArchive: string.Empty);
zipFile.MaxOutputSegmentSize = 100 * 1000000;
zipFile.Save("c:\\users\\me\\test.zip");
}
Finally, I've tried the 7z.dll and SharpCompress. Using the Command Line and the 7z.exe file, the following works perfectly:
7z.exe a "c:\users\me\test.zip" "c:\Windows\Fonts" -v100m
But the following code gives the error "Value does not fall within the expected range."
SevenZipCompressor.SetLibraryPath("c:\\program files\\7-zip\\7z.dll");
var compressor = new SevenZipCompressor();
compressor.CompressionMethod = CompressionMethod.Lzma2;
compressor.CustomParameters.Add("v", "100m");
compressor.CompressDirectory("c:\\windows\\fonts\\", "c:\\users\\me\\test.zip");
I've also tried the following (having tried to figure out how the command line switches work in SharpCompress) which does create a zip file, but doesn't split it up:
SevenZipCompressor.SetLibraryPath("c:\\program files\\7-zip\\7z.dll");
var compressor = new SevenZipCompressor();
compressor.CompressionMethod = CompressionMethod.Lzma2;
compressor.CustomParameters.Add("mt", "on");
compressor.CustomParameters.Add("0", "LZMA2:c=100m");
compressor.CompressDirectory("c:\\windows\\fonts\\", "c:\\users\\me\\test.zip");
Does anyone know why any of the above methods aren't working? Or are there any other ways that people have got working that I haven't tried yet?
Thanks!
I am not aware of a library that supports the PKZIP split zip file format.
It's an old question, but Ionic is working. Maybe a little bit tricky, but ok. My first version also creates a set of files that I can't then unzip. But after changing the order of commands, the output can be unzipped.
private static void CreateEncryptedZipFile(string filename, string to, FileInfo fi, string password)
{
using (var zipFile = new Ionic.Zip.ZipFile())
{
zipFile.Password = password;
zipFile.Encryption = Ionic.Zip.EncryptionAlgorithm.WinZipAes256;
zipFile.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
zipFile.AddFile(filename, directoryPathInArchive: string.Empty);
zipFile.MaxOutputSegmentSize = 1024*1024*128;
zipFile.Save(to + ".zip");
}
createXMLInfo(fi, to);
}

Using .NET ZipArchive to zip entire directories AS well as extra info

I inherited some code that makes use of ZipArchive to save some information from the database. It uses BinaryFormatter to do this. When you look at the zip file with 7-zip (for example), you see a couple of folders and a .txt file. All is working well. I simply want to modify the code to also have a folder in the ZipArchive called "temp" that consists of files and folders under C:\temp. Is there an easy way to add a entry (ZipArchiveEntry?) that consist of an entire folder or the disc? I saw "CreateEntryFromFile" in the member methods of ZipArchive, but no CreateEntryFromDirectory. Or perhaps there's some other simple way to do it? Anyone have example code? I should say that C:\temp could have variable number of files and directories (that have child directories and files, etc.) Must I enumerate them somehow, create my own directories use CreateEntryFromFile? Any help is appreciated.
Similarly, when I read the ZipArchive, I want to take the stuff related to C:\temp and just dump it in a directory (like C:\temp_old)
Thanks,
Dave
The answer by user1469065 in Zip folder in C# worked for me. user1469065 shows how to get all the files/directories in the directory (using some cool "yield" statements) and then do the serialization. For completeness, I did add the code to deserialize as user1469065 suggested (at least I think I did it the way he suggested).
private static void ReadTempFileStuff(ZipArchive archive) // adw
{
var sessionArchives = archive.Entries.Where(x => x.FullName.StartsWith(#"temp_directory_contents")).ToArray();
if (sessionArchives != null && sessionArchives.Length > 0)
{
foreach (ZipArchiveEntry entry in sessionArchives)
{
FileInfo info = new FileInfo(#"C:\" + entry.FullName);
if (!info.Directory.Exists)
{
Directory.CreateDirectory(info.DirectoryName);
}
entry.ExtractToFile(#"C:\" + entry.FullName,true);
}
}
}

Pass Multiple files to function

I have a function deals with xml files after determine it by OpenFileDialog and it supports multi selection of files
openFileDialog1.Multiselect = true;
openFileDialog1.Filter = "*.xml|*.XML";
openFileDialog1.Title="Please Select Xml file to convert ";
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
foreach (string file in openFileDialog1.FileNames)
{
//string lsit contain file names
Filestoconvert.Add(file);
}
}
and the function make process on it.
for (int i = 0; i < Filestoconvert.Count; i++)
{
XmlProcess( Filestoconvert[i]);
}
but when select files only last selected file pass to the function and other files just read in the list only.
I want to select multiple files and pass it to this function to process these files one by one without passing files manually to it.
Can any one explain how to do that ? Give me piece of code or link?
Without seeing the implementation of XmlProcess it is a guessing game. You say that this method doesn't work as expected, yet you don't show us how this method works. How can you expect anyone to help you?
Nonetheless, if you want to pass multiple files to the function, just change the signature from
void XmlProcess(string file) // should be something very similar
to
void XmlProcess(IEnumerable files)
Now you can pass an array, a list or any other object implementing the IEnumerable interface.

Read all text files in a folder with StreamReader

I am trying to read all .txt files in a folder using stream reader. I have this now and it works fine for one file but I need to read all files in the folder. This is what I have so far. Any suggestions would be greatly appreciated.
using (var reader = new StreamReader(File.OpenRead(#"C:\ftp\inbox\test.txt")))
You can use Directory.EnumerateFiles() method instead of.
Returns an enumerable collection of file names that match a search
pattern in a specified path.
var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt");
foreach (string currentFile in txtFiles)
{
...
}
You can call Directory.EnumerateFiles() to find all files in a folder.
You can retrieve the files of a directory:
string[] filePaths = Directory.GetFiles(#"c:\MyDir\");
Therefore you can iterate each file performing whatever you want. Ex: reading all lines.
And also you can use a file mask as a second argument for the GetFiles method.
Edit:
Inside this post you can see the difference between EnumerateFiles and GetFiles.
What is the difference between Directory.EnumerateFiles vs Directory.GetFiles?

Using the SharpSVN api are there any methods available to get the number of lines contained in a file at a Revision without Exporting it?

I was just wondering if I missed anything inside the documentation that would allow me to get the number of lines contained in a file at a certain revision (or even number of lines changed from a SvnChangeItem, that would be nice too) without having to directly export the file to the filesystem and parse through it counting each line.
Any help would be appreciated. Thanks.
Nope, your stuck with exactly the solution you named. Export to temp file, count the lines, delete the file. A fairly expensive operation if your doing this file-by-file. It may be better to fetch the entire repo if you need to line-count every file and reuse the working directory for future runs.
The meta data (like current line count) is not contained within the repository but you can get the file without doing messy temp files.
For brevity, excluded code to iterate over revisions etc.
using (var client = new SvnClient())
{
using (MemoryStream memoryStream = new MemoryStream())
{
client.Write(new SvnUriTarget(urlToFile), memoryStream);
memoryStream.Position = 0;
var streamReader = new StreamReader(memoryStream);
int lineCount = 0;
while (streamReader.ReadLine() != null)
{
lineCount++;
}
}
}

Categories