Copy file from source directory to destination C# - 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);
}
}

Related

Removing part of DirectoryName

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.

Moving files using SSIS and Script Component

I need to write a code in script component in SSIS that will move files to corresponding folders. Files that I'm getting are usually named, for example "Dem323_04265.45.23.4", "Dem65_459.452.56", "Ec2345_456.156.7894" and I need to move them to a corresponding folders. The name of my folders are "Oklahoma City (323)", "New York(65)".. I need to move those files to matching folders, so for example "Dem323_04265.45.23.4" would go to folder "Oklahoma City (323)". I need to modify my code so the number that is located between first two or three letter and underline matches number located in parenthesis. I've been working on this for several days already and I'm new with ssis and c#, so any help would be appreciated. This is the code I have so far:
public void Main()
{
string filename;
// string datepart;
bool FolderExistFlg;
filename = Dts.Variables["User::FileName"].Value.ToString();
// datepart = (filename.Substring(filename.Length - 12)).Substring(0, 8);
var folderNumber = Regex.Match(
filename,
//Dts.Variables["OutputMainFolder"].Value.ToString(),
#"\(([^)]*)\)").Groups[1].Value;
FolderExistFlg = Directory.Exists(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + folderNumber);
if (!FolderExistFlg)
{
Directory.CreateDirectory(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + folderNumber);
}
File.Move(Dts.Variables["SourceFolder"].Value.ToString() + "\\" + filename + "\\" + folderNumber,
Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + filename);
Dts.TaskResult = (int)ScriptResults.Success;
}
#region ScriptResults declaration
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
Here you go, the below snippet would move the files as per the match criteria. You need to take care of the source input as per your configuration.
string filePath = #"C:\Packages\StackOverflow";
//string fileName = string.Empty;
//get list of files
string[] filePaths = Directory.GetFiles(filePath);
//get list of folders
string[] dirPaths = Directory.GetDirectories(filePath);
//loop through the files and move them
foreach(string fileNames in filePaths)
{
string[] pathArr = fileNames.Split('\\');
string fileName = pathArr.Last().ToString();
int index = fileName.IndexOf('_');
string fileNamePart = fileName.Substring(0, index);
//get the first numeric part of the filename to perform the match
var fileNameNumPart = Regex.Replace(fileNamePart, "[^0-9]", "");
//find related directory
var dirMatch = dirPaths.FirstOrDefault(stringToCheck => stringToCheck.Contains(fileNameNumPart.ToString()));
if (dirMatch != null)
{
// move would fail if file already exists in destination
if (!File.Exists(dirMatch + '\\' + fileName))
{
File.Move(fileNames, dirMatch + '\\' + fileName);
}
}
}

Get files from a folder that I have created in Xamarin.Android

I want get all files from an external storage folder(wall_e_imgs)..Here are codes-
public void getImages()
{
var path1 = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath.ToString();
string path = System.IO.Path.Combine(path1, "wall_e_imgs");
//var files= System.IO.Directory.GetFiles(Android.OS.Environment.ExternalStorageDirectory.ToString() + "wall_e_imgs");
//var files = System.IO.Directory.GetFiles(path);
//string path = Android.OS.Environment.ExternalStorageDirectory.ToString() + "/wall_e_imgs";
//File directory=new File(path);
Java.IO.File directory = new Java.IO.File(path);
Java.IO.File[] files = directory.ListFiles();//always count is 0 even though there are lot files there
foreach (var i in files)
{
FileInfo info = new FileInfo(i.Name);
if (info.Name.Contains("Wall_e"))
{
di.Add(new DownloadedImages { Path1 = info.DirectoryName, Name1 = info.FullName });
}
}
}
But it always give 0 files even though there are lot of files.
Try this
var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "yourfoldername";
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
var filesList = Directory.GetFiles(folder);
foreach (var file in filesList)
{
var filename = Path.GetFileName(file);
}
Try something like this:
// Use whatever folder path you want here, the special folder is just an example
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "wall_e_imgs");
if (Directory.Exists(folderPath))
{
var files = Directory.EnumerateFiles(folderPath);
foreach (var file in files)
{
// Do your stuff
}
}
Please note that this uses the Directory class from System.IO, not Java.IO
ffilelist will contain a list of mp3 files in "/storage/emulated/0/Music/"
string phyle;
string ffilelist = "";
public void listfiles()
{
try
{
var path1 = "/storage/emulated/0/Music/";
var mp3Files = Directory.EnumerateFiles(path1, "*.mp3", SearchOption.AllDirectories);
foreach (string currentFile in mp3Files)
{
phyle = currentFile;
ffilelist = ffilelist + "\n" + phyle;
}
//playpath(phyle); // play the last file found
}
catch (Exception e9)
{
Toast.MakeText(ApplicationContext, "ut oh\n"+e9.Message , ToastLength.Long).Show();
}
}

Creating unique files in another directory

Currently i am taking in multiple .txt files from a directory i have specified (sourceDirectory). I am generating new .csv files with the same name as the .txt files - one .csv file for each .txt file.
However i want to generate these new files in another directory which i have specified (directoryPath). If i run my program once it creates these files in the initial directory, however if i run my program again it now generates the files in the destination directory.
The following is my code where i complete the above:
static void Main(string[] args)
{
string sourceDirectory = #"C:directoryWhereTXTFilesAre";
var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt", SearchOption.AllDirectories);
foreach (string currentFile in txtFiles)
{
readFile(currentFile);
}
string directoryPath = #"C:\destinationForCSVFiles";
}
I then create the new .csv files name based on the original .txt file like this:
static FileStream CreateFileWithUniqueName(string folder, string fileName, int maxAttempts = 1024)
{
var fileBase = Path.GetFileNameWithoutExtension(fileName);
var ext = Path.GetExtension(fileName);
// build hash set of filenames for performance
var files = new HashSet<string> (Directory.GetFiles(folder));
for (var index = 0; index < maxAttempts; index++)
{
// first try with the original filename, else try incrementally adding an index
var name = (index == 0)
? fileName
: String.Format("{0} ({1}){2}", fileBase, index, ext);
// check if exists
var fullPath = Path.Combine(folder, name);
string CSVfileName = Path.ChangeExtension(fullPath, ".csv");
if (files.Contains(CSVfileName))
continue;
// try to create the file
try
{
return new FileStream(CSVfileName, FileMode.CreateNew, FileAccess.Write);
}
catch (DirectoryNotFoundException) { throw; }
catch (DriveNotFoundException) { throw; }
catch (IOException)
{
}
}
I don't see why it's creating the .csv files initially in the same directory that the .txt files are in and then second time i run my code it creates them in the directoryPath.
Desired output: sourceDirectory left as it is with only .txt files and directoryPath to hold the .csv files.
The only other place i call CreateFileWithUniqueName is within my readFile method, the code is below:
using (var stream = CreateFileWithUniqueName(#"C:destinationFilePath", currentFile))
{
Console.WriteLine("Created \"" + stream.Name + "\"");
newFileName = stream.Name;
Globals.CleanedFileName = newFileName;
}
It seems that you are passing the full filename of the source file. This confuses the Path.Combine inside the CreateFileWithUniqueFilename because you are falling in this subtle remarks found on the documentation of Path.Combine
paths should be an array of the parts of the path to combine. If the
one of the subsequent paths is an absolute path, then the combine
operation resets starting with that absolute path, discarding all
previous combined paths.
You can fix it easily with
using (var stream = CreateFileWithUniqueName(#"C:\destinationFilePath",
Path.GetFileName(currentFile)))
{
Console.WriteLine("Created \"" + stream.Name + "\"");
newFileName = stream.Name;
Globals.CleanedFileName = newFileName;
}
Or better extract the filename without path inside the CreateFileWithUniqueName
static FileStream CreateFileWithUniqueName(string folder, string fileName, int maxAttempts = 1024)
{
var fileBase = Path.GetFileName(fileName);
fileBase = Path.GetFileNameWithoutExtension(fileBase);
var ext = Path.GetExtension(fileBase);
also, you should build your CSVfileName using the cleaned filename
var name = (index == 0)
? String.Format("{0}{1}", fileBase, ext);
: String.Format("{0} ({1}){2}", fileBase, index, ext);
var fullPath = Path.Combine(folder, name);
string CSVfileName = Path.ChangeExtension(fullPath, ".csv");
if (files.Contains(CSVfileName))
continue;

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);
}
}

Categories