Removing part of DirectoryName - c#

I'm trying to remove part of a path in a string but it doesn't actually remove anything. I'm not sure what I'm doing wrong in this method.
string path = AppDomain.CurrentDomain.BaseDirectory + "/FastDL-Generator-Input/";
DirectoryInfo d = new DirectoryInfo(path + "materials/");
FileInfo[] Files = d.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo file in Files)
{
string filePath = file.DirectoryName.Replace(path, "");
status3.Text = filePath;
}
It doesn't run with any errors, but it's not removing anything. This is the output
"C:\Users\*****\source\repos\FastDL Generator\FastDL Generator\bin\Debug\FastDL-Generator-Input\materials\test"
It should be printing
"materials\test"
instead. If you can provide any advice, I would greatly appreciate it.

You're using a forward slash in your path, I ran your code on my machine using back slash and it worked as you expected.
Try this:
string path = AppDomain.CurrentDomain.BaseDirectory + "FastDL-Generator-Input\\";
DirectoryInfo d = new DirectoryInfo(path + "materials\\");
FileInfo[] Files = d.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo file in Files)
{
string filePath = file.DirectoryName.Replace(path, "");
status3.Text = filePath;
}

You need to change these two lines:
string path = AppDomain.CurrentDomain.BaseDirectory + "/FastDL-Generator-Input/";
DirectoryInfo d = new DirectoryInfo(path + "materials/");
To this:
string path = AppDomain.CurrentDomain.BaseDirectory + "FastDL-Generator-Input\\";
DirectoryInfo d = new DirectoryInfo(path + "materials\\");
Note the change in direction of the slashes in the path.

Related

How can i get files specific files names from directory?

string[] list = Directory.GetFiles(countriesMainPath + "\\" + currentDownloadCountry, "*.jpg");
But not only gif i want to specify that also it will be only files that contains the name infrared. For example i have files name 0infrared.gif and also 0visible.gif and i want to get all the files that are infrared.
This will get you all files with infrared in file name and with extension jpg
string[] list = Directory.GetFiles(countriesMainPath + "\\" + currentDownloadCountry,
"*infrared*.jpg");
string[] list = Directory.GetFiles(
countriesMainPath + "\\" + currentDownloadCountry,
"*infrared*.*");
This will return all the files contain infrared in their file name.
I think this may be what you look for. ref: MSDN
public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
{
string[] searchPatterns = searchPattern.Split('|');
List<string> files = new List<string>();
foreach (string sp in searchPatterns)
files.AddRange(System.IO.Directory.GetFiles(path, sp, searchOption));
files.Sort();
return files.ToArray();
}
Usage
var wantedImgs = GetFiles(
dirYouWant, "*infrared*.jpg|*infrared*.gif",
earchOption.TopDirectoryOnly);
string partialName = "infrared";
DirectoryInfo dir = new DirectoryInfo(#"c:\");
FileInfo[] filesInDir = dir.GetFiles("*" + partialName + "*.*");
foreach (FileInfo foundFile in filesInDir)
{
string fullName = foundFile.FullName;
Console.WriteLine(fullName);
}
maybe *infrared*.(jpg|gif) will work

Copy file from source directory to destination C#

I would like to copy my files from source folder to my dest. folder
The location / URL(Name of the column in the table) I got it from here GetDataByGeneralRoot();
Now I would like to copy those file from that URL to a new directory.
What I have done is:
DataSet1.T_DocumentsDataTable docTab = doc.GetDataByGeneralRoot();
string gerneralRootPath = docTab.Rows[0]["URL"].ToString();
gerneralRootPath = gerneralRootPath.Remove(gerneralRootPath.IndexOf("PDF") + 4);
string datadirectory = "//ch-s-0001535/G/inetpub/DocAddWeb/DataSource/";
string final = datadirectory + gerneralRootPath;
foreach (string path in Directory.GetFiles(final, "*.*", SearchOption.AllDirectories))
{
string t = path.Substring(path.IndexOf("\\") + 1);
File.Copy(t, t.Replace(final + t, rootFolderAbsolutePath));
}
My issue / problem is how can I say that I want to get only the files from URL that I got from my method GetDataByGeneralRoot and not all the files what is now happening.
HERE is how my tabel looks like:
I think you want something like this
public void copyAll(DataSet ds, Doc doc, string rootPath, string rootTargetPath)
{
ds.T_DocumentsDataTable docTab = doc.GetDataByGeneralRoot();
string datadirectory = "//ch-s-0001535/G/inetpub/DocAddWeb/DataSource/";
string final = datadirectory + rootPath;
foreach (var row in docTab.Rows)
{
var sourceFile = "//ch-s-0001535/G/inetpub/DocAddWeb/DataSource/" + row["URL"].ToString();
string targetPath = rootTargetPath + row["URL"].ToString();
File.Copy(sourceFile, rootTargetPath);
}
}

Accessing USB Drives from 'Computer'

I'm trying to copy files over from the desktop to a USB drive programmatically. However, when trying to run this code, I am geting an error stating that part of the path could not be found:
if (dr == DialogResult.Yes)
{
string selected = comboBox1.GetItemText(comboBox1.SelectedItem);
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filefolder = #"\UpgradeFiles";
string fileLocation = filePath + filefolder;
if (!Directory.Exists(fileLocation))
{
Directory.CreateDirectory(fileLocation);
}
else if (Directory.Exists(fileLocation))
{
DirectoryInfo di = new DirectoryInfo(fileLocation);
FileInfo[] fileList = di.GetFiles();
foreach (FileInfo file in fileList)
{
string DrivePath = Environment.GetFolderPath(
Environment.SpecialFolder.MyComputer);
string CopyToDrive = comboBox1.Text;
file.CopyTo(DrivePath + CopyToDrive, false);
}
}
}
The combobox contains the selected drive letter. Am I approaching this wrong when trying to add "computer\driveletter"?
Your File.CopyTo(DrivePath + CopyToDrive, false) should be:
File.CopyTo(CopyToDrive + File.Name, false);
but with a bit of syntactic sugar like using Path.Combine or String.Format instead of just "+".
The issue is that File.CopyTo requires both the directory AND filename of the end location, when you're just providing the directory. This can be seen in the documentation for the method call here: https://msdn.microsoft.com/en-us/library/f0e105zt(v=vs.110).aspx

Copy everything in a Directory and rename copied Files

I try to copy everything in a Folder to another, in this case from "sourceFolder" to "targetFolder".
Lets say "sourceFolder" would have two Files in it and 2 subfolder with one additional File:
(i try to show it)
//sourceFolder
//├File1.txt
//├File2.txt
//├Subfolder1
//| └File3.txt
//|
//└Subfolder2
// └File4.txt
Now I'm trying to copy all of those files and subfolders from "sourceFolder" to "targetFolder", the subfolders shall be titled the same and on the Files i would to add "a" in front of "Filex.txt"(Exaple: "aFilex.txt")
Thats what im tring to get:
//targetFolder
//├aFile1.txt
//├aFile2.txt
//├Subfolder1
//| └aFile3.txt
//|
//└Subfolder2
// └aFile4.txt
current Code:
string[] sourceDirectoryFiles = Directory.GetFiles(sourceFolderTextbox.Text);
string[] sourceDirectorysubfolders = Directory.GetDirectories(targetFolderTextbox.Text);
string sourcedirectory = sourceFolderTextbox.Text;
string targetdirectory = targetFolderTextbox.Text;
if (Directory.Exists(sourceDirectorysubfolders[0]))
{
foreach (string sourceFilePath in sourceDirectorysubfolders)
{
if (!Directory.Exists(sourceFilePath))
{
Directory.CreateDirectory(sourceFilePath.Replace(sourcedirectory, targetdirectory));
}
}
}
foreach (string sourceFilePath in sourceDirectoryFiles )
{
string newsourcefilePath = String.Empty;
string newfilePath = String.Empty;
string FileName = System.IO.Path.GetFileName(sourceFilePath);
newsourcefilePath = sourcedirectory + "\\a" + FileName;
System.IO.File.Copy(sourceFilePath, newfilePath ,true)
}
I hope, I asked clear :)
otherwise I'll answer your questions :)
I'm not good at English or programming so constructive criticism is welcome :)
Have modified the solution in this SO Question to suit your needs. Hope it helps.
void Copy(string sourcePath, string targetPath)
{
foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
string newPath;
foreach (string srcPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))
{
newPath = srcPath.Replace(sourcePath, targetPath);
newPath = newPath.Insert(newPath.LastIndexOf("\\") + 1, "a"); //prefixing 'a'
newPath = newPath + ".example";
File.Copy(srcPath, newPath, true);
}
}

Displaying desired files only in asp.net

DirectoryInfo Dir = new DirectoryInfo(Server.MapPath(strheadlinesid));
FileInfo[] FileList = Dir.GetFiles("*.txt", SearchOption.AllDirectories);
In the Place of *.txt ,I want to mention some more file extensions how can I do that.
I used another type of approach but I have a small problem in it when I use the FI as hyperlink it's giving total path.but I want to print only the file name not fullpath.
string supportedExtensions = "*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg,*.wmf,*.emf,*.xbm,*.ico,*.eps,*.tif,*.tiff,*.g01,*.g02,*.g03,*.g04,*.g05,*.g06,*.g07,*.g08";
foreach (string FI in Directory.GetFiles(Server.MapPath(strheadlinesid), "*.*", SearchOption.AllDirectories).Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower())))
{
Response.Write("<td><a href= view5.aspx?file=" + strheadlinesid + "\\" + FI + " target=_self;> " +
FI + "</a></td>");
}
Try
string fileFilter = "*.wma,*.jpeg,*.txt";
string[] fileExt = fileFilter.Split(',');
FileInfo[] fileInfo = null;
DirectoryInfo dir = new DirectoryInfo("D:\\Test");
List<FileInfo[]> listFileInfo = new List<FileInfo[]>();
foreach (string strVar in fileExt)
{
fileInfo = dir.GetFiles(strVar, SearchOption.AllDirectories);
listFileInfo.Add(fileInfo);
}

Categories