Check files of a zip file exists in another directory - c#

No Content check
I have two directories C:\Workspace\TestProject\ZipFileA.zip\ as Directory 'A' and C:\Workspace\Reports\Latest\ as Directory 'B' ......Inside directory A, multiple Log files are there and inside Directory 'B' multiple log files are there...
I need to check each log file of Directory 'A' is present in Directory 'B' or not. Incase If any log file of Directory 'A' is NOT exists or doesn't present in Directory 'B' then i need to throw an exception or return false. Basically, files of A directory should be present in 'B' directory. No Issues if 'B' contains additional files which are not in 'A'
How can i check and return bool/throw exception?

Use the Intersect method to return values present in both lists
var dirAFiles = System.IO.Directory.GetFiles("c:\\dirA").Select(s => System.IO.Path.GetFileName(s));
var dirBFiles = System.IO.Directory.GetFiles("c:\\dirB").Select(s => System.IO.Path.GetFileName(s));
var filesInDirAAndDirB = dirAFiles.Intersect(dirBFiles );
Don't forget to select the filename only because GetFiles returns the full path of the files
To throw an exception just exclude the files existing in A and B from the list of A. If any file exists, you have an error
if (dirAFiles.Except(filesInDirAAndDirB).Any())
{
// error
}
EDIT:
Other answers that were deleted since were much better since it is not necessary to intersect the file list from both directories. A simple
dirAFiles.Except(dirBFiles).Any()
is sufficient to find out if any element in dirA exists without being present in dirB.
Oh well, there's not kill like overkill :p

Related

checking if file exists in FileInfo[]

I am creating a Windows application in which on a button click it will check a folder specified in the .config file for '.SQL' files and if it has any files then the application will execute the SQL file in the specified DB.
So for checking the '.sql' file in a directory I used the below code:
DirectoryInfo d = new DirectoryInfo(path);
FileInfo[] sqlfiles = d.GetFiles("*.sql");
Now, I want to add an IF condition to check any such file exist, if not I want to place a warning message.
So could you please help me to find how to check whether any such '.sql' file exist in that directory using the above code?
You can use .Any() to check if any array, or list, or IEnumerable has items. IMO it's a much clearer intent than list.Count > 0.
DirectoryInfo d = new DirectoryInfo(path);
FileInfo[] sqlfiles = d.GetFiles("*.sql");
if(sqlFiles.Any())
{
// At least one .sql file exists
}
else
{
// No sql files exist
}
(Cue arguments about iterators etc.)

System.IO.File.Delete invalid characters

I'm trying to delete all files in a directory by doing this:
System.IO.File.Delete(directoriodestino_imagenes + #"\*.*");
Where, directoriodestino_imagenes = "C:\\dcm\\patients\\NAME_LASTNAME\\DCM\\".
And I get this:
{"Illegal characters in path."}
Any hints what I may be doing wrong?
It's the wildcard character. You cannot delete multiple files using Delete method. You either need to delete the whole folder (look at the Delete folder method at http://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx) or just remove them one by one. E.g. like in Deleting multiple files with wildcard
Actually it is possible to delete Files in a folder. Here is how I do it.
string directory = #"C:\File Downloader\DownloadedFile\";
string[] file = Directory.GetFiles(directory); // get all files in the folder.
foreach (string fileName in file )
File.Delete(fileName );

How to create a new path that contains the same path as the source but with a different root?

I'm about to develop a software in C# that must select random folders (in a scenario with 10.000 folders more or less) that follow these rules:
select only the ones which contains files;
the software must stop the selection when the size of selected folder is 8GB;
when I copy a single folder, I need to keep the whole path of that folder (if c:\folder\temp\hello is the copied one, I want to keep d:\COPIED\folder\temp\hello);
I think I will do somethings like:
analyze the whole list of folder starting from an assigned root;
select random "line" in this list, moving it to the "selected list", counting the size;
when I reach 8GB, I stop this first phase, and I start to copy it;
I think here it is not a big trouble. What do you think about? Any suggestions?
My real problem will to "recreate" the whole path for each single folder when I move it.
How can I do it? Create folder for each level with C# API or is there a workaround?
So the last paragraph is the question? I understand it in the following way:
How to create a new path that contains the same path as the source but
with a different root?
Then you can use the Path class and it's static methods + String.Substring to get the new path.
D:\Copied is your root destination folder which you use in Path.Combine. Then you have to add the old-path without it's root-folder(there is no method in Path for this, i'll use Substring):
var rootDest = #"D:\Copy"; // your root directory
var pathSource = #"C:\Test\Test.txt"; // a sample file
var root = Path.GetPathRoot(pathSource); // C:\
var oldPathWithoutRoot = pathSource.Substring(root.Length); // Test\Test.txt
var newPath = Path.Combine(rootDest, oldPathWithoutRoot); // D:\Copy\Test\Test.txt
Then use File.Copy to copy all files in the folder from the old to the new path.
You have to check if the directory exists and create it otherwise:
var targetDir = Path.GetDirectoryName(newPath);
if (!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir); // D:\Copy\Test
}
File.Copy(pathSource, newPath);

Selective deletion of files in folder according to the name

I would like to know (using c#) how I can delete files in a certain directory whose name contains *mhz.prj.
In fact there are several files in this folder and I want to delete only Amhz.prj Bmhz.prj for example. My problem is that the end of the filename is important.
This will loop through C:\MyDir and delete any files with the extension prj.
foreach(var file in Directory.GetFiles(#"C:\MyDir", "*.prj"))
{
File.Delete(Path.GetFullPath(file));
}

C# How to grep the last word from a directory path?

I have a program that "greps" out various directory paths from a log text file and prints various results according to the word.
Examples of Directory paths:
C:/Documents and Settings/All Users/Desktop/AccessData FTK Imager.lnk
C:/Documents and Settings/All Users/Start Menu/Programs/AccessData
C:/Documents and Settings/Administrator/Desktop/AccessData FTK Imager.exe:Zone.Identifier
Therefore how can I grep out the file or folder name after the last "/"? This is to help the program to identify between files and folder. Please do take note of the multiple "." and white spaces found within a directory paths. etc "Imager.exe:Zone.Identifier". Therefore it is difficult to use if(!name.contains()".")
Etc. How to get the "AccessData FTK Imager.lnk" or "AccessData" or "AccessData FTK Imager.exe:Zone.Identifier" from the path STRING?!
May someone please advise on the methods or codes to solve this problem? Thanks!
The codes:
if (!token[7].Contains("."))
{
Console.WriteLine("The path is a folder?");
Console.WriteLine(token[7]);
Console.WriteLine(actions);
MacActions(actions);
x = 1;
}
Use the Path class when working with file paths, and use the File and Directory class when working with actual files and folders.
string str1=#"C:/Documents and Settings/All Users/Desktop/AccessData FTK Imager.lnk";
string str2=#"C:/Documents and Settings/All Users/Start Menu/Programs/AccessData";
string str3=#"C:/Documents and Settings/Administrator/Desktop/AccessData FTK Imager.exe:Zone.Identifier";
Console.WriteLine(Path.GetFileName(str1));
Console.WriteLine(Path.GetFileName(str2));
Console.WriteLine(Path.GetFileName(str3));
outputs:
AccessData FTK Imager.lnk
AccessData
Zone.Identifier <-- it chokes here because of the :
This class operates on strings, as I do not have those particular files and/or folders on my system. Also it's impossible to determine whether AccessData is meant to be a folder or a file without an extension.
I could use some common sense and declare everything with an extension to be a file (Path.GetFileExtension can be used here) and everything else to be a folder.
Or I could just check it the string in question is indeed a file or a folder on my machine using (File.Exists and Directory.Exists respectively).
if (File.Exists(str2))
Console.WriteLine("It's a file");
else if (Directory.Exists(str2))
Console.WriteLine("It's a folder");
else
Console.WriteLine("It's not a real file or folder");
Use Path.GetFileName.
The characters after the last directory character in path. If the last character of path is a directory or volume separator character, this method returns String.Empty.
This is to help the program to identify between files and folder
There is no way to determine is a path represents a file or folder, unless you access the actual file system. A directory name like 'Foo.exe' would be perfectly valid, and a file with no extension ('Foobar') would be valid too.
how about tokenized it with "/" like what you're doing ... and then you'll know that the last token is the file, and whatever before it is the path.
You can simply split the whole string by /
e.g.:
string a="C:/Documents and Settings/All Users/Desktop/AccessData FTK Imager.lnk";
string[] words=a.split('/');
int len=words.length;
so now words[len] returns the data after last slash(/)..
I hope you understand...
I guess you only have a string that represents the name of the file, if that is the case you can't really be sure. It's totally ok to have a folder namen something like Folder.doc. So if you don't have access to the actual file system it is hard to check. You can get close though using regular expression like:
(.*\\)(.+)(\..*)
Try it on: http://www.regexplanet.com/simple/index.html
If you get any output in group number 3 it's likely that it is a file and not a folder. If you don't get some output try this direct after:
(.*\\)(.+)(\..*)?
That will give you the folder in group 2.

Categories

Resources