C# copy last file from a folder into another generated folder - c#

I'm trying to get a latest file from a path and copying it, then paste it into a generated folder.
This is what I tried so far:
// This Method is called if the function/method CopyContent is invoked by the user or a bound event.
// Return true, if this component has to be revalidated!
public bool OnCopyContent(int arg)
{
// Get latet file from the specificed Folder
var directory = new DirectoryInfo(#""+sourceFolderPath);
var myFile = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
// Newly Created Folder Name
string generatedFolderName = destinationFolderName;
// Newly Creted Folder Path (i.e C://Users/Desktop) Cretge it on desktop with name "Paste me here "
string generatedPathString = System.IO.Path.Combine(destinationFolderPath, generatedFolderName);
if (!File.Exists(generatedPathString))
System.IO.Directory.CreateDirectory(generatedPathString);
// Copy the Latet file to the newly Created Folder on the Desktop
string destFile = Path.Combine(#""+destinationFolderPath, myFile.Name);
File.Copy(myFile.FullName, destFile, true);
return false;
}
What im trying to do is
1 : I have Specifed Folder Path , i want to copy it's latest file in it depending on timee
2: Create new Folder on Desktop with name " NewlyAdded"
3: Paste the Copied File from the Specifed Folder to the Newly Created Folder

now my issue is how to copy it
simply : take the file name ans pass it with the destination folder to a string,
then pass the file.FullName to Copy() method and it'll be copied.
This code tested and worked.
EDIT : Added a line to generate folder if not exist, and copy the file to it.
string newFolder = "NewlyAdded";
string path = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
newFolder
);
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
var directory = new DirectoryInfo(#"Sourcd folder");
var myFile = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
string destFile = Path.Combine(path, myFile.Name);
System.IO.File.Copy(myFile.FullName, destFile, true);
the true as a last parameter is to overwrite if exist.

Looking at the documentation, the first parameter is the path of the original file...
https://msdn.microsoft.com/en-us/library/9706cfs5(v=vs.110).aspx
I have trying to copy it however im not sure now how to pass it in
You use the file path of the original, not the FileInfo itself!
Like this:
var directory = new DirectoryInfo(#"C:\");
FileInfo myFile = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
string filePath = myFile.FullName;
You'd use this filePath variable, not the FileInfo instance you're currently using.

if you coudn't copy string file then open your current file which you want to copy in binary read (rb) and store that in variable.
after write that file in particular directory by using binary write
may be it should help you

Related

not able to get correct file path for subfolder file

in this I am trying to load all the excel data from specified folderpath and its subfolder present inside it to sql server... Problem is I am able to read the main folder and subfolder, but while taking the data from sub folder file it taking the path of main folder for that sub folder file
example: file path - d:\test
sub directory : d:\test\test2
inside subdirectory my file is present but when iterating it is reading the path of sub directory file as : d:\test\file_name
please help in this
```DirectoryInfo directory = new DirectoryInfo(#FolderPath);
FileInfo[] files = directory.GetFiles("*.xlsx", SearchOption.AllDirectories);```
// Directory structure:
// C:\Temp\ExcelFiles\Excel1.xlsx
// C:\Temp\ExcelFiles\SubFolder\Excel2.xlsx
var path = #"C:\Temp\ExcelFiles";
var allExcelFilesInPathAndSubFolders = Directory.GetFiles(path, "*.xlsx", SearchOption.AllDirectories);
This approach returns the expected 2 Excel file names as string array (i.e. C:\Temp\ExcelFiles\Excel1.xlsx and C:\Temp\ExcelFiles\SubFolder\Excel2.xlsx).
The approach in your post returns an array of FileInfo. You can get all relevant information from that; the name with or without path, the file extension, and using Path.GetFileNameWithoutExtension you can get the name without extension.
// Directory structure:
// C:\Temp\ExcelFiles\Excel1.xlsx
// C:\Temp\ExcelFiles\SubFolder\Excel2.xlsx
var path = #"C:\Temp\ExcelFiles";
DirectoryInfo directory = new DirectoryInfo(path);
FileInfo[] files = directory.GetFiles("*.xlsx", SearchOption.AllDirectories);
// Excel1.xlsx
var firstFileName = files.First().Name;
// Excel1
var firstFileNameWithoutExtension = Path.GetFileNameWithoutExtension(files.First().Name);
// .xlsx
var fileFileExtension = files.First().Extension;
// C:\Temp\ExcelFiles\Excel1.xlsx
var firstFileFullName = files.First().FullName;

How to get a specific file from directory in C#

Using Directory.GetFiles() returns all the files in the directory as follows:
var sqlFiles = Directory.GetFiles($"{AppDomain.CurrentDomain.BaseDirectory}Content\\DbScripts\\","*.sql");
Actually I need a specific file from that directory. What I have tried so far as follows but don't work!
var localizationSqlFile = Directory.GetFiles($"{AppDomain.CurrentDomain.BaseDirectory}Content\\DbScripts\\Localizations.sql").FirstOrDefault();
It throws expection:
The directory name is invalid.\r\n
Is there any method in C# to get a single file from a directory? If not then what will be most efficient way?
If you want to get the bytes of a certain file and you already have the full path, you can use the static method File.ReadAllBytes
var fileBytes = File.ReadAllBytes(myPath);
If you want to get file infos, you can create a new FileInfo object
var fileInfo = new FileInfo(myPath);
If you just want to check, if a file exists, you can also use the method File.Exist
if (File.Exists(myPath))
You can get the file from your sqlFiles returned
var sqlFiles = Directory.GetFiles($"{AppDomain.CurrentDomain.BaseDirectory}Content\\DbScripts\\","*.sql");
var yourFile = sqlFiles.FirstOrDefault(x=> Path.GetFileName(x) == "Localizations.sql");

Need to copy files from one location to another if path matches neglecting the root folder(s)

I need to copy files from one location to another if path matches. In this scenario (pic attached), I have a folder C:\OldFiles\New Folder\ which contains Text.txt and I have another folder D:\NewFiles\New Folder\ which contains Text.txt. Notice that the root folder and the subfolder are different but the names of the file and its folder are exactly the same.
Developing a windows form C# tool which points to a path containing the new files which should replace the old ones in a different path. Help please? Click here to view my scenario.
string fileName = "test.txt";
string sourcePath = #"C:\OldFiles\New Folder\";
string targetPath = #"D:\NewFiles\New Folder\ ";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
//"Source path does not exist!
}
string sourcePath = #"C:\OldFiles\NewFolder";
string targetPath = #"D:\NewFiles\NewFolder ";
var a = sourcePath.Split('\\');
var b = targetPath.Split('\\');
string a1 = a[a.Length - 2]; //this will return OldFiles
string a2 = a[a.Length-1]; //this will return NewFolder
string b1 = b[b.Length - 2]; // this will return NewFiles
string b2 = b[b.Length-1]; // this will return NewFolder
//you get the idea now use what ever you want with it in you if statement
// pass true to replace existing if exists in destination
File.Copy("source path here", "destination path here", true);

Create Directory will multiple names passed by parameter C#

I have to create multiple folders as e.g.
Directory.CreateDirectory("PATH\\" + _year + "filetosave.txt");
while "PATH\\" is the full path where the folder will reside, _year is the parameter and "filetosave.txt" is the file which is to be saved in respective folder.
And at run time, it should create respective folders with years in the folder name containing respective files to save.
Whereas .CreateDirectory() method only accepts string path or string path, security access as parameters.
How will we create these parameterized folders?
How can we make a check that a specified directory already exists or not?
var path = Path.Combine("PATH\\", _year.ToString(), "filettosave.txt");
Directory.CreateDirectory(path);
Directory.CreateDirectory
Creates all directories and subdirectories in the specified path unless they already exist.
Emphasis mine.
As commented, use Path.Combine when trying to build system paths:
var root = "Path";
var year = "2016";
var filename = "filetosave.txt";
var path = Path.Combine(root, year, filename);
// path = Path\2016\filetosave.txt
Directory.CreateDirectory(path);
In general, use System.IO.Path.Combine to build paths. It simplifies this task.
string dir = System.IO.Path.Combine(rootPath, _year.ToString());
Directory.CreateDirectory(dir);
string file = System.IO.Path.Combine(dir, "filetosave.txt");
FileStream fs = File.Create(file)

GetTempFileName() and saving to the AppData folder

In the below code, the files are being saved in the debug folder of the project, I want to store the files in the appdata folder under a generic specified folder!
AViewModel vm = DataContext as AViewModel;
var table = vm.FileSelectedItem;
if (table != null)
{
var filename = System.IO.Path.GetTempFileName();
File.WriteAllBytes(table.FileTitle, table.Data);
Process prc = new Process();
prc.StartInfo.FileName = table.FileTitle;
prc.Start();
}
//table.FileTitle is the name of the file stored in the db
// eg:(test1.docx, test2.pdf, test3.txt, test4.xlsx)
//table.Data is public byte[] Data { get; set; } property
// which stores the files coming from the db.
I am looking at GetFolderPath and trying something like this now
System.IO.Path.GetTempFileName(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
Thanks for any replys!
GetTempFileName returns a full path to a file in the user's temp path. You can't use that to create a file within a specific folder.
Given that you want to store within the AppData folder already, perhaps you are after something more like:
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "YourCompany\\YourProduct\\Output");
var filename = Path.Combine(path, table.FileTitle);
File.WriteAllBytes(filename, table.Data);
Process.Start(filename);
In case you want to create randomly named file under AppData, you can try
Guid.NewGuid().ToString("N")
That'll give you random string with reasonable certainty it is unique. For folder under AppData:
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Guid.NewGuid().ToString("N"));
Note: at least put it into some subfolder, AppData is folder shared with all other apps.

Categories

Resources