string.IsNullOrEmpty to combine another directory - c#

I want ask to find directory name it (folder1) to combine.
But if directory not exist, i want to find another directory name it (folder2) to combine.
What should i put to it?
Here the code:
public static string DataDirectory
{
get
{
if (string.IsNullOrEmpty(Directory))
return null;
return Path.Combine(Directory, "Data/folder1");
}
}
Thanks.

Directory.Exists should work fine
public static string DataDirectory
{
get
{
if (string.IsNullOrEmpty(Directory))
return null;
// Use Path.Combine just one time
string firstFolder = Path.Combine(Directory, "Data/folder1");
if(Directory.Exists(firstFolder)
return Path.Combine(firstFolder);
else
return Path.Combine(Directory, "Data/folder2");
}
}

you could also do something like this to first check if there are any directories, then use linq to order the directories and select the first element.
public static string GetDataDirectory(string root)
{
var directoryList = Directory.GetDirectories(root);
if (!directoryList.Any())
return null;
directoryList = directoryList.OrderBy(dir => dir).ToArray();
return directoryList.First();
}

Related

C# Recursive folder search does not work properly

I need help, because I've written a method that should find a special directory on a computer that definitely exists.
First I've written a method that will be go through every drive on a computer and open up for every drive the recursive method.
private string LocateOnDrives()
{
string result = string.Empty;
string[] drives = Directory.GetLogicalDrives();
foreach (string drive in drives)
{
string buffer = this.Locate(drive);
if (buffer.EndsWith(SEARCH_PATTERN))
{
return buffer;
}
}
return result;
}
And this is the method that is called for every drive:
private string Locate(string directory)
{
string result = string.Empty;
try
{
string[] dirs = Directory.GetDirectories(directory);
foreach (string dir in dirs)
{
if (dir.EndsWith(SEARCH_PATTERN))
{
return dir;
}
else
{
result = this.Locate(dir);
}
}
}
catch { }
return result;
}
The try catch is necessary, because there are some directories with no permission. I have the permission for the sought folder and when i debug this, it will jump into the if condition that it has found and set the local 'result' to this sought folder. Up to this point it really makes that what was my intention. But the recursive method will search further and the overall return is string.Empty!
I already did something link this:
private string tragetDir;
private string Locate(string directory)
{
string result = string.Empty;
try
{
string[] dirs = Directory.GetDirectories(directory);
foreach (string dir in dirs)
{
if (dir.EndsWith(DEFAULT_GTAV_DIRECTORY_NAME))
{
targetDir = dir;
}
else
{
result = this.Locate(dir);
}
}
}
catch { }
return result;
This is working for me, but not what I wanted to have, because it should be possible that the recursive method will return this wanted folder…
It is late for me and I just want to fix this little mistake!
Can someone help me out, because I am desperate, THANKS!
When you find a match and return it, then unwind once in your nested calls to Locate(), you assign the match to result but then keep progressing with the loop, when you actually want to break out of it.
result = this.Locate(dir, SEARCH_PATTERN);
if (result.EndsWith(SEARCH_PATTERN))
{
break;
}
Also, you might consider just catching the UnauthorizedAccessException since that's the one it'll throw if you don't have permission to a particular directory.
This is a solution I tried and it worked for me now:
private string Locate(string directory)
{
string result = string.Empty;
string[] dirs = new string[0];
try
{
dirs = Directory.GetDirectories(directory);
}
catch { /* Ignore */ }
foreach (string dir in dirs)
{
if (dir.EndsWith(SEARCH_PATTERN))
{
result = dir;
break;
}
else
{
result = this.Locate(dir);
if (result.EndsWith(SEARCH_PATTERN))
{
break;
}
}
}
return result;
}
First I had to check if the current "dir" in the loop was already the sought folder. If not, the loop had to browse inside this folder and if the result inside this folder isn't the sought folder the loop had to going on and search on or in the next folder in loop.
In any case that the right directory was found, the loop will "break" and return the result!
This is it!

Creating a getter for specific Directory visual C#

I'm relatively new to Visual C# and I have been searching for a bit now. I cant find an actual solution to my problem (perhaps because i'm searching for the wrong way or thing).
So I want to create a getter that gives me the directory so I can convert the path name to a string.
This is the code I am using
(I already know that getDirectories gives an array of strings)
public Directory getDBDirectory() {
Directory db;
if (!Directory.Exists(itemFolder)) {
Console.WriteLine("Couldn't find directory.. is it created?");
} else {
db = Directory.GetDirectories(itemFolder);
}
return db;
}
To get the path for subdirectories:
string[] db = Directory.GetDirectories(itemFolder);
If you want to get Directory Info:
DirectoryInfo dir = new DirectoryInfo(somepath);
which you can access its name nad path by dir.Name and dir.FullName
Directory is a Static Class. I assumes you need to get all folders inside itemFolder.
So just change the return type to string[] instead, like this:
public string[] getDBDirectory() {
//Directory db; //no need
if (!Directory.Exists(itemFolder)) {
Console.WriteLine("Couldn't find directory.. is it created?");
return null;
} else {
return Directory.GetDirectories(itemFolder);
}
}
or if you just want to check if it exist:
public string getDBDirectory() {
if (!Directory.Exists(itemFolder)) {
Console.WriteLine("Couldn't find directory.. is it created?");
return null;
} else {
return itemFolder;
}
}
or if I understand you right, you can use Directory.CreateDirectory(itemFolder); that will Create If Not Exists.

Opening files in another computer c#

I have a program that a button, when clicked, executes a sound located in my download folder. My question is how to execute the sound on another computer if the path for finding it is different.
You need the path to a file to run it. If you don't have the path - you have to search for it.
Pick a base directory where you think the file is. If you don't know where - that will be the whole drive.
Write a recursive function that would search said folder recursively.
Test each file by what ever your search condition is, i.e. file name, file hash, etc.
For example:
string SearchForFile(string searchPath, Func<string, bool> searchPredicate)
{
try
{
foreach (string fileName in Directory.EnumerateFiles(searchPath))
{
if (searchPredicate(fileName))
{
return fileName;
}
}
foreach (string dirName in Directory.EnumerateDirectories(searchPath))
{
var childResult = SearchForFile(dirName, searchPredicate);
if (childResult != null)
{
return childResult;
}
}
return null;
}
catch (UnauthorizedAccessException)
{
return null;
}
}
Usage:
var filePath = SearchForFile(#"C:\", x => Path.GetFileName(x) == "yourFileName.mp3");

Efficient way to get the file list and copy to local directory?

I was trying to get the list of files in my remote directory and check only the file has name "test"; then copy to my local directory.
Just did a simple thing here but can someone please let me know the best way to handle this scenario.
class Program
{
static void Main(string[] args)
{
var getfiles = new fileshare.Program();
string[] filteredfiles =getfiles.GetFileList();
bool b;
foreach (string file in filteredfiles)
{
if(b=file.Contains("test"))
{
getfiles.copytolocal(file);
}
}
}
private string[] GetFileList()
{
string[] filepaths = Directory.GetFiles(#"\\testserver\dev");
return filepaths;
}
private void copytolocal(string filename)
{
File.Copy(filename, #"C:\" + filename);
}
}
Even i just stuck up when i was copy the file,the filename contains the whole directory inside the filename so filename look like "\\testserver\dev\test.txt". So it failed to copy in to local.
You can use DirectoryInfo to filter down to any file that contains the string "test":
private FileInfo[] GetFileList(string pattern)
{
var di = new DirectoryInfo(#"\\testserver\dev");
return di.GetFiles(pattern);
}
and then:
foreach (var file in GetFileList("*test*"))
{
getfiles.copytolocal(file.FullName);
}
You're looking for Path.GetFileName() (which returns a string).

How to convert a relative path to an absolute path in a Windows application?

How do I convert a relative path to an absolute path in a Windows application?
I know we can use server.MapPath() in ASP.NET. But what can we do in a Windows application?
I mean, if there is a .NET built-in function that can handle that...
Have you tried:
string absolute = Path.GetFullPath(relative);
? Note that that will use the current working directory of the process, not the directory containing the executable. If that doesn't help, please clarify your question.
If you want to get the path relative to your .exe then use
string absolute = Path.Combine(Application.ExecutablePath, relative);
This one works for paths on different drives, for drive-relative paths and for actual relative paths. Heck, it even works if the basePath isn't actually absolute; it always uses the current working directory as final fallback.
public static String GetAbsolutePath(String path)
{
return GetAbsolutePath(null, path);
}
public static String GetAbsolutePath(String basePath, String path)
{
if (path == null)
return null;
if (basePath == null)
basePath = Path.GetFullPath("."); // quick way of getting current working directory
else
basePath = GetAbsolutePath(null, basePath); // to be REALLY sure ;)
String finalPath;
// specific for windows paths starting on \ - they need the drive added to them.
// I constructed this piece like this for possible Mono support.
if (!Path.IsPathRooted(path) || "\\".Equals(Path.GetPathRoot(path)))
{
if (path.StartsWith(Path.DirectorySeparatorChar.ToString()))
finalPath = Path.Combine(Path.GetPathRoot(basePath), path.TrimStart(Path.DirectorySeparatorChar));
else
finalPath = Path.Combine(basePath, path);
}
else
finalPath = path;
// resolves any internal "..\" to get the true full path.
return Path.GetFullPath(finalPath);
}
It's a bit older topic, but it might be useful for someone.
I have solved a similar problem, but in my case, the path was not at the beginning of the text.
So here is my solution:
public static class StringExtension
{
private const string parentSymbol = "..\\";
private const string absoluteSymbol = ".\\";
public static String AbsolutePath(this string relativePath)
{
string replacePath = AppDomain.CurrentDomain.BaseDirectory;
int parentStart = relativePath.IndexOf(parentSymbol);
int absoluteStart = relativePath.IndexOf(absoluteSymbol);
if (parentStart >= 0)
{
int parentLength = 0;
while (relativePath.Substring(parentStart + parentLength).Contains(parentSymbol))
{
replacePath = new DirectoryInfo(replacePath).Parent.FullName;
parentLength = parentLength + parentSymbol.Length;
};
relativePath = relativePath.Replace(relativePath.Substring(parentStart, parentLength), string.Format("{0}\\", replacePath));
}
else if (absoluteStart >= 0)
{
relativePath = relativePath.Replace(".\\", replacePath);
}
return relativePath;
}
}
Example:
Data Source=.\Data\Data.sdf;Persist Security Info=False;
Data Source=..\..\bin\Debug\Data\Data.sdf;Persist Security Info=False;

Categories