checking if file exists in FileInfo[] - c#

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.)

Related

Check if xml exists in a directory and read it

Hello everyone I'm new to c#. I want to read an xml file if it exists in a directory. 1) How can I read it? 2) If there are multiple xml files how to read those at the same time?
XmlTextReader xtr = new XmlTextReader(path)
string pathD = #"H:\UsersDirectory";
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] TXTFiles = di.GetFiles("*.xml");
if (TXTFiles.Length != 0)
{
//how can I read the file?
}
If you know the name of the file, you can use:
File.Exists("YourPath");
to check if the File exists. If not, you can use:
Directory.GetFiles("ContainingDirectory");
to get a list of all files in a directory, and then loop through them, checking if they end with .xml, to find your file.
As for reading the content of the file, you can use
File.ReadAllText("FilePath");
to read the content of your XML-File. For multiple files, you can obviously just call this function multiple times, once for every file.
If you want to edit XML too, I'd like to direct you towards XPathNavigator: https://learn.microsoft.com/en-us/troubleshoot/developer/visualstudio/csharp/language-compilers/xml-xpathnavigator

Is there an algorithms that can list all file in the folder (for C#)?

Hello StackOverflow community,
I'm working for a C# web application that can show all necessary files in one folder. For example, you have a folder named "Maps" that stores all information about New York City. I will describe this folder here: The bolded word is folders.
Folder Maps:
->NewYorkCity
->>satellite.png
->>coordinates.txt
->>bridges.png
->>Road1
->>>satellite1.png
->>>roads.txt
->>>houses.png
As you can see, inside folder Maps we have folder NewYorkCity, and inside of this, we have folder Road1. Now I want to collect all files that have "*.png" type. It means I want to collect all images inside the root folder. The problem here is the algorithm to collect the file. I have thought to use "for loops" but I don't know the number of subfolders so I assumed it was impossible.
Here is the code to list the file with specified type that I have used but it works for files that in one folder and doesn't have any subfolders.
DirectoryInfo dInfo = new DirectoryInfo(zipPath); //Assuming Test is your Folder
FileInfo[] Files = dInfo.GetFiles("*.png"); //Getting Text files
string str = "";
foreach (FileInfo file in Files)
{
str = str + ", " + file.Name;
}
I hope you understand my question. Thank you.
You could start by reading the documentation, where you would find System.IO.DirectoryInfo.
Create a DirectoryInfo instance, and use, depending on what you want/need, any of its methods
EnumerateDirectories()
EnumerateFiles()
EnumerateFileSystemInfos()
Like so:
DirectoryInfo di = new DirectoryInfo(#"c:\Maps");
foreach (var fsi in di.EnumerateFileSystemInfos("*", SearchOptions.AllDirectories)
{
// Do something useful with fsi here
}

Move Directory Into Current Directory C#

I want to do something simple. Take the contents of folder A and move the files and folders into a folder within folder A. Then make folder A hidden.
The code below is getting an exception of hiddenTarget is not found.
Directory.Create(hiddenTarget) is not helping
There must be a simple way to do this. Currently I am attempting to make a temp directory. Put all files from the current directory in it. Then Move the temp directory to the current directory. Then make the current directory hidden.
Here is the code in issue..
string tempFolder = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), "tempTarget");
//Directory.CreateDirectory(tempFolder);
Directory.Move(currentTarget, tempFolder);
string hiddenTarget = Path.Combine(currentTarget, #".bak");
//Directory.CreateDirectory(hiddenTarget);
Directory.Move(tempFolder, hiddenTarget);
DirectoryInfo di = new DirectoryInfo(currentTarget);
di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
So you have two issues here first is that your hidden target cannot start with a '.' because as pointed out in the comments that is illegal in NTFS.
As you can see File Explorer doesn't like this syntax.
As pointed out by #Dour High Arch here is the link to the relevant information: Naming Files, Paths, and Namespaces
Your next issue is that the move is destroying the original directory structure. Therefore, your steps need to be as follows:
1) Move to a temporary directory to avoid any issues with the two processes (file system & your process) fighting for access.
2) Due to the fact that the Directory.Move in step #1 destroyed the original source directory. Recreate the destroyed source folder.
3) Then move into the desired nested folder. This move operation will automatically create the desired sub-directory. Step #2 is required because for whatever reason I'm still looking into Directory.Move cannot automatically create the structure without the source directory already existing.
string currentTarget = #"C:\A";
string hiddenTarget = #"C:\A\Subfolder";
string tempTarget = #"C:\Temp";
Directory.Move(currentTarget, tempTarget);
Directory.CreateDirectory(currentTarget);
Directory.Move(tempTarget, hiddenTarget);
DirectoryInfo di = new DirectoryInfo(currentTarget);
di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
Update
From an engineering perspective you really should be performing copies if you really care about the data being moved. It may be slower, but will help prevent any horrible things from happening to the data. You should check whether or not these directories exist first before creating them. Exception handling within this example is at a minimum as well. What I'm really trying to stress here is handle the data that is being moved with care!
static void Main(string[] args)
{
string sourceDir = #"C:\Src";
string tempDir = #"C:\Temp";
string destDir = Path.Combine(sourceDir, "Dest");
// Could optionally check to verify that the temp directory already exists here and destroy it if it does.
// Alternatively, pick a really unique name for the temp directory by using a GUID, Thread Id or something of that nature.
// That way you can be sure it does not already exist.
// Copy to temp, then destroy source files.
CopyDirectory(sourceDir, tempDir);
Directory.Delete(sourceDir, true);
// Copy to dest
CopyDirectory(tempDir, destDir);
// Hide the source directory.
DirectoryInfo di = new DirectoryInfo(sourceDir);
di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
// Clean up the temp directory that way copies of the files aren't sitting around.
// NOTE: Be sure to do this last as if something goes wrong with the move the temp directory will still exist.
Directory.Delete(tempDir, true);
}
/// <summary>
/// Recursively copies all subdirectories.
/// </summary>
/// <param name="sourceDir">The source directory from which to copy.</param>
/// <param name="destDir">The destination directory to copy content to.</param>
static void CopyDirectory(string sourceDir, string destDir)
{
var sourceDirInfo = new DirectoryInfo(sourceDir);
if (!sourceDirInfo.Exists)
{
throw new DirectoryNotFoundException($"Source directory does not exist or could not be found: '{sourceDir}'");
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDir))
{
Directory.CreateDirectory(destDir);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = sourceDirInfo.GetFiles();
foreach (FileInfo file in files)
{
string tempPath = Path.Combine(destDir, file.Name);
file.CopyTo(tempPath, false);
}
// Copy subdirectories
DirectoryInfo[] subDirs = sourceDirInfo.GetDirectories();
foreach (DirectoryInfo subdir in subDirs)
{
string tempPath = Path.Combine(destDir, subdir.Name);
CopyDirectory(subdir.FullName, tempPath);
}
}
Here are a few more links regarding the above.
MSDN - How to: Copy Directories
Stack Overflow - How to copy the entire contents of directory in C#?

How to copy a directory from local drive to a shared network using asp.net C#

Hello I am attempting to copy a directory and its subdirectories from my D drive to a shared network but I continue getting the error as
Exception:
Could not find a part of the path '/Projects/08.ASP.NETProjects/ProjectName/'.
My C# copy code:
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(D drive path);
var destinationpath = "file:///BZ0025BZV43/Projects/08.ASP.NETProjects/ProjectName/";
var uri = new Uri(destinationpath);
var destinationurl = uri.AbsolutePath;
foreach (System.IO.FileInfo mydirectory in directory.GetFiles())
mydirectory .CopyTo(destinationurl);
I am new to FileHandlers. Please help.
Try to use uri.LocalPath instead of uri.AbsolutePath.
Also, be aware that you are trying to copy a file into a directory. But you have to copy the file into another file of that directory. (Directories are files too, basically).
So to do that check if the target directory exists and create it when necessary. Then replace .copyTo(destinationUrl) with .copyTo(Path.Combine(uri.LocalPath, mydirectory.Name)) and you should be good to go. And please rename the variable mydirectory to file or something similar.
Also note that you are not copying the directory tree recursively. So if you want to recurse the tree, you have to check for subdirectories and copy the files in that hierarchy, too.
You can also check out this example: http://msdn.microsoft.com/de-de/library/bb762914(v=vs.110).aspx

Check files of a zip file exists in another directory

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

Categories

Resources