changing absolute Path to relative Path - c#

How i would like to change my absolute Path to relative Path.
anyone can help?
this is my Code
string activeDirectory = #"X:\Temp\";
string[] files = Directory.GetFiles(activeDirectory);
foreach (string fileName in files)
{
.....
}

I would prefer files.Select(f => f.Substring(activeDirectory.Length)).
That means 'Skip x chars and return the rest'.

Related

Create Folders out of PDF-Names, crop the foldername and move them into the folder

I want to create a program that gets all the .pdf-filenames (ex: test.pdf -> test) and creates an folder with that name. Also the foldername should be cropped after the first "-" (ex: A539B2AA3-GG-81234278 -> A539B2AA3).
This is the code I have made yet, but I have no clue how to proceed. I'm still a beginner, trying to learn C#:
string path = #"C:\pdfs\";
string[] filenames;
int lengtharray;
filenames = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly)
.Where(s => (Path.GetExtension(s).ToLower() == ".pdf")).ToArray();
lengtharray = filenames.Length;
If someone can help me, I would be very happy.
Sincerely,
breadhead
You can use this code.
1) Directory.GetFiles has a wildcard support, so you can use *.pdf to search for file.
2) I added some validation in the loop, in case there are PDF file that does not have -.
string path = #"C:\pdfs\";
foreach(var file in Directory.GetFiles(path, "*.pdf", SearchOption.TopDirectoryOnly))
{
var newName = Path.GetFileName(file).Split('-');
if (!newName.Any())
continue;
Directory.CreateDirectory(Path.Combine(path,newName[0]));
}
You can simplify your file query, use filenames = Directory.GetFiles(path, "*.pdf", .... and skip the Where()-part. To loop through your list, you can use a foreach (file in filenames). As mentioned you can get the new filename with file.Split("-")[0] or with a regular expression. Then create a directory with Directory.CreateDirectory and move the file in with System.IO.File.Move("oldfilename", "newfilename");. Now you have all the bricks and you only need to glue them together

How to create a folder out of the first few letters of a filename?

So I checked out the basic things but I'd like to do the following:
I have 5 files let's say: X1_word_date.pdf, XX1_word_date.pdf, etc...
I'd like to create a folder structure like: C:\PATH\X1, C:\PATH\XX1, etc...
So how do I take the first letters before the '_' in the file names and put it into a string?
My idea is that I use the Directory.CreateDirectory and than combine the main path and the strings so I get the folders.
How do I do that? Help appreciated.
string fileName = "X1_word_date.pdf";
string[] tokens = fileName.Split('_');
string myPath = "C:\\PATH\\";
Directory.CreateDirectory( myPath + tokens[0]);
Something like this should work. Using Split() will also allow for numbers greater than 9 to be dealt with
Supposed that your files is a List<string> which contains the file name (X2_word_date.pdf,...)
files.ForEach(f => {
var pathName= f.Split('_').FirstOrDefault();
if(!string.IsNullOrEmpty(pathName))
{
var directoryInfo = DirectoryInfo(Path.Combine(#"C:\PATH", pathName));
if(!directoryInfo.Exists)
directoryInfo.Create();
//Then move this current file to the directory created, by FileInfo and Move method
}
})
With simple string methods like Split and the System.IO.Path class:
var filesAndFolders = files
.Select(fn => new
{
File = fn,
Dir = Path.Combine(#"C:\PATH", Path.GetFileNameWithoutExtension(fn).Split('_')[0].Trim())
});
If you want to create that folder and add the file:
foreach (var x in filesAndFolders)
{
Directory.CreateDirectory(x.Dir); // will only create it if it doesn't exist yet
string newFileName = Path.Combine(x.Dir, x.File);
// we don't know the old path of the file so i can't show how to move
}
Or using regex
string mainPath = #"C:\PATH";
string[] filenames = new string[] { "X1_word_date.pdf", "X2_word_date.pdf" };
foreach (string filename in filenames)
{
Match foldernameMatch = Regex.Match(filename, "^[^_]+");
if (foldernameMatch.Success)
Directory.CreateDirectory(Path.Combine(mainPath, foldernameMatch.Value));
}
Using the bigger picture starting with only your Source and Destination directory.
We can list all files we need to move with Directory.GetFiles.
In this list We first isolate the filename with GetFileName.
Using simple String.Split you have the new directory name.
Directory.CreateDirectory will create directories unless they already exist.
To move the file we need its destination path, a combinaison of the Destination directory path and the fileName.
string sourceDirectory = #"";
string destDirectory = #"";
string[] filesToMove = Directory.GetFiles(sourceDirectory);
foreach (var filePath in filesToMove) {
var fileName = Path.GetFileName(filePath);
var dirPath = Path.Combine(destDirectory, fileName.Split('_')[0]);
var fileNewPath= Path.Combine(dirPath,fileName);
Directory.CreateDirectory(dirPath);// If it exist it does nothing.
File.Move(filePath, fileNewPath);
}

Check if a folder exists in the filepath

I want to loop through all sub folders and files in a folder and check whether a particular filename contains a folder say "X" in its path (ancestor). I dont want to use string comparison.Is there a better way?
Answering your specific question (the one that is in the title of your question, not in the body), once you have the filename (which other answers tell you how to find), you can do:
bool PathHasFolder(string pathToFileName, string folderToCheck)
{
return Path.GetDirectoryName(pathToFileName)
.Split(Path.DirectorySeparatorChar)
.Any(x => x == folderToCheck);
}
This will work only with absolute paths... if you have relative paths you can complicate it further (this requires the file to actually exist though):
bool PathHasFolder(string pathToFileName, string folderToCheck)
{
return new FileInfo(pathToFileName)
.Directory
.FullName
.Split(Path.DirectorySeparatorChar)
.Any(x => x == folderToCheck);
}
You can use Directory.GetFiles()
// Only get files that begin with the letter "c."
string[] dirs = Directory.GetFiles(#"c:\", "c*");
Console.WriteLine("The number of files starting with c is {0}.", dirs.Length);
foreach (string dir in dirs)
{
Console.WriteLine(dir);
}
https://msdn.microsoft.com/en-us/library/6ff71z1w(v=vs.110).aspx
You can use recursive search like
// sourcedir = path where you start searching
public void DirSearch(string sourcedir)
{
try
{
foreach (string dir in Directory.GetDirectories(sourcedir))
{
DirSearch(dir);
}
// If you're looking for folders and not files take Directory.GetDirectories(string, string)
foreach (string filepath in Directory.GetFiles(sourcedir, "whatever-file*wildcard-allowed*"))
{
// list or sth to hold all pathes where a file/folder was found
_internalPath.Add(filepath);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
So in your case you're looking for folder XYZ, use
// Takes all folders in sourcedir e.g. C:/ that starts with XYZ
foreach (string filepath in Directory.GetDirectories(sourcedir, "XYZ*")){...}
So if you would give sourcedir C:/ it would search in all folders available on C:/ which would take quite a while of course

How to find the file by its partial name?

How can I get the full filename?
For example:
I have a file named 171_s.jpg that is stored on the hard disc.
I need to find the file by its partial name, i.e. 171_s, and get the full name.
How can I implement this?
Here's an example using GetFiles():
static void Main(string[] args)
{
string partialName = "171_s";
DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(#"c:\");
FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles("*" + partialName + "*.*");
foreach (FileInfo foundFile in filesInDir)
{
string fullName = foundFile.FullName;
Console.WriteLine(fullName);
}
}
Update - Jakub answer is more efficient way to do.
ie, use System.IO.Directory.GetFiles()
http://msdn.microsoft.com/en-us/library/ms143316.aspx
The answer has been already posted, however for an easy understanding here is the code
string folderPath = #"C:/Temp/";
DirectoryInfo dir= new DirectoryInfo(folderPath);
FileInfo[] files = dir.GetFiles("171_s*", SearchOption.TopDirectoryOnly);
foreach (var item in files)
{
// do something here
}
You could use System.IO.Directory.GetFiles()
http://msdn.microsoft.com/en-us/library/ms143316.aspx
public static string[] GetFiles(
string path,
string searchPattern,
SearchOption searchOption
)
path
Type: System.String
The directory to search.
searchPattern
Type: System.String
The search string to match against the names of files in path. The parameter cannot end in two periods ("..") or contain two periods
("..") followed by DirectorySeparatorChar or
AltDirectorySeparatorChar, nor can it contain any of the characters in
InvalidPathChars.
searchOption
Type: System.IO.SearchOption
One of the SearchOption values that specifies whether the search operation should include all subdirectories or only the current
directory.
You can do it like this:
....
List<string> _filesNames;
foreach(var file in _directory)
{
string name = GetFileName(file);
if(name.IndexOf(_partialFileName) > 0)
{
_fileNames.Add(name);
}
}
....
Simple as that:
string path = #"C:\example\directory";
string searchPattern = "*171_s*";
string[] filePaths = Directory.GetFiles(path, searchPattern,SearchOption.AllDirectories);

Get folder name from full file path

How do I get the folder name from the full path of the application?
This is the file path below,
c:\projects\root\wsdlproj\devlop\beta2\text
Here "text" is the folder name.
How can I get that folder name from this path?
See DirectoryInfo.Name:
string dirName = new DirectoryInfo(#"c:\projects\roott\wsdlproj\devlop\beta2\text").Name;
I think you want to get parent folder name from file path. It is easy to get.
One way is to create a FileInfo type object and use its Directory property.
Example:
FileInfo fInfo = new FileInfo("c:\projects\roott\wsdlproj\devlop\beta2\text\abc.txt");
String dirName = fInfo.Directory.Name;
Try this
var myFolderName = #"c:\projects\roott\wsdlproj\devlop\beta2\text";
var result = Path.GetFileName(myFolderName);
You could use this:
string path = #"c:\projects\roott\wsdlproj\devlop\beta2\text";
string lastDirectory = path.Split(new char[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).Last();
Simply use Path.GetFileName
Here - Extract folder name from the full path of a folder:
string folderName = Path.GetFileName(#"c:\projects\root\wsdlproj\devlop\beta2\text");//Return "text"
Here is some extra - Extract folder name from the full path of a file:
string folderName = Path.GetFileName(Path.GetDirectoryName(#"c:\projects\root\wsdlproj\devlop\beta2\text\GTA.exe"));//Return "text"
I figured there's no way except going into the file system to find out if text.txt is a directory or just a file. If you wanted something simple, maybe you can just use:
s.Substring(s.LastIndexOf(#"\"));
In this case the file which you want to get is stored in the strpath variable:
string strPath = Server.MapPath(Request.ApplicationPath) + "/contents/member/" + strFileName;
Here is an alternative method that worked for me without having to create a DirectoryInfo object. The key point is that GetFileName() works when there is no trailing slash in the path.
var name = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar));
Example:
var list = Directory.EnumerateDirectories(path, "*")
.Select(p => new
{
id = "id_" + p.GetHashCode().ToString("x"),
text = Path.GetFileName(p.TrimEnd(Path.DirectorySeparatorChar)),
icon = "fa fa-folder",
children = true
})
.Distinct()
.OrderBy(p => p.text);
This can also be done like so;
var directoryName = System.IO.Path.GetFileName(#"c:\projects\roott\wsdlproj\devlop\beta2\text");
Based on previous answers (but fixed)
using static System.IO.Path;
var dir = GetFileName(path?.TrimEnd(DirectorySeparatorChar, AltDirectorySeparatorChar));
Explanation of GetFileName from .NET source:
Returns the name and extension parts of the given path. The resulting
string contains the characters of path that follow the last
backslash ("\"), slash ("/"), or colon (":") character in
path. The resulting string is the entire path if path
contains no backslash after removing trailing slashes, slash, or colon characters. The resulting
string is null if path is null.

Categories

Resources