Copy files from one path to another path in c# - c#

If
frompath = "c:\\progfiles\\mobileapp\\es-gl\\a.dll"
and
topath = "c:\\progfiles\\mobileapp\\es-gl\\a.dll"
I want to copy file from frompath to topath.
If topath does not exist, then the directories and sub directories must get created and the file a.dll must copy from frompath to topath. I am using c# .net Compact Framework.

I think you are after the System.IO namespace. Using File.Copy can provide the solution.
And Directory.Exists / create can make the directory is not existing.
var fileName = "tmp.txt";
var from = #"c:\temp\" + fileName;
var to = #"c:\temp\1\";
if (!Directory.Exists(to))
Directory.CreateDirectory(to);
File.Copy(from, to + fileName);
You can go for FileInfo aswell. (Also in the System.IO namespace)
var file = new FileInfo(#"c:\temp\tmp.txt");
var to = #"c:\temp\1\";
if (!Directory.Exists(to))
Directory.CreateDirectory(to);
file.CopyTo(to + file.Name);

Related

Create zip file from all files in folder

I'm trying to create a zip file from all files in a folder, but can't find any related snippet online. I'm trying to do something like this:
DirectoryInfo dir = new DirectoryInfo("somedir path");
ZipFile zip = new ZipFile();
zip.AddFiles(dir.getfiles());
zip.SaveTo("some other path");
Any help is very much appreciated.
edit: I only want to zip the files from a folder, not it's subfolders.
Referencing System.IO.Compression and System.IO.Compression.FileSystem in your Project
using System.IO.Compression;
string startPath = #"c:\example\start";//folder to add
string zipPath = #"c:\example\result.zip";//URL for your ZIP file
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);
string extractPath = #"c:\example\extract";//path to extract
ZipFile.ExtractToDirectory(zipPath, extractPath);
To use files only, use:
//Creates a new, blank zip file to work with - the file will be
//finalized when the using statement completes
using (ZipArchive newFile = ZipFile.Open(zipName, ZipArchiveMode.Create))
{
foreach (string file in Directory.GetFiles(myPath))
{
newFile.CreateEntryFromFile(file, System.IO.Path.GetFileName(file));
}
}
Referencing System.IO.Compression and System.IO.Compression.FileSystem in your Project, your code can be something like:
string startPath = #"some path";
string zipPath = #"some other path";
var files = Directory.GetFiles(startPath);
using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
{
foreach (var file in files)
{
archive.CreateEntryFromFile(file, file);
}
}
}
In some folders though you may have problems with permissions.
To make your zipfile portable on UNIX system, you should pay attention to:
Compression.ZipFile support for Unix Permissions
For instance, one may use mod "644":
var entry = newFile.CreateEntryFromFile(file, file);
entry.ExternalAttributes |= (Convert.ToInt32("644", 8) << 16);
This does not need loops. For VS2019 + .NET FW 4.7+ did this...
Find ZipFile in Manage Nuget Packages browse, or use
https://www.nuget.org/packages/40-System.IO.Compression.FileSystem/
Then use:
using System.IO.Compression;
As an example, below code fragment will pack and unpack a directory (use false to avoid packing subdirs)
string zippedPath = "c:\\mydir"; // folder to add
string zipFileName = "c:\\temp\\therecipes.zip"; // zipfile to create
string unzipPath = "c:\\unpackedmydir"; // URL for ZIP file unpack
ZipFile.CreateFromDirectory(zippedPath, zipFileName, CompressionLevel.Fastest, true);
ZipFile.ExtractToDirectory(zipFileName, unzipPath);

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)

How to move a file from a default directory to another?

It sounds simple but it is not. I am trying to move a file that i made it like this:
string newFileName = string.Format("{0}-{1}-{2}-t{3:00}-{4:00}.txt", 2013, 10, 5, 05, 06);
It is going to look like: 2013-10-5-05-06.txt, from the default directory (..\bin\debug\2013-10-5-05-06.txt) to another directory (c:\Users\Public\Folder). I want to keep the name of the file so that other files having almost the same name (small difference between) being moved to the same folder. I tried several methods (Path.Combine(), string.Concat()..) without success.
Just use this snippet
string CurrentFileNameAndPath; //the path the file you want to move
string newPath; //only the new the folderPath
System.IO.FileInfo FileYouWantToMove = new System.IO.FileInfo(CurrentFileNameAndPath);
string NewFileNameAndPath = newPath + "\\" + FileYouWantToMove.Name; //remember that using fullname will get the folder and filename
FileYouWantToMove.MoveTo(NewFileNameAndPath);
So lets use this as an example i have this file C:/Dir1/file1.txt and I want to change its directory to C:/Dir2/ right? then it will be like this
string CurrentFileNameAndPath = #"C:/Dir1/file1.txt";
string newPath = #"C:/Dir2/";
System.IO.FileInfo FileYouWantToMove = new System.IO.FileInfo(CurrentFileNameAndPath);
string NewFileNameAndPath = newPath + "\\" + FileYouWantToMove.Name;
FileYouWantToMove.MoveTo(NewFileNameAndPath);
the result will the that file in C:/Dir1/file1.txt will be now in C:/Dir2/file1.txt it have been moved and maintened the same file name and extension
Something like this is actually pretty trivial
var srcFile = "..\bin\debug\2013-10-5-05-06.txt";
var destFolder = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
var destFile = Path.Combine(destFolder, Path.GetFileName(srcFile));
File.Move(srcFile, destFile);
Just keep in mind that Move can throw various exceptions e.g. IOException / UnauthorizedAccessException etc. so it would be wise to handle these where appropriate.

Access file in Resources C#

I would like to import to registry a .reg file that exist in project resources.
The way to import a reg file uses the path to the reg file:
Process proc = new Process();
proc = Process.Start("regedit.exe", "/s " + "path\to\file.reg");
Is it possible to do so with a file from resources? how do I get its path?
If it is in the project folder. i-e. The folder in which the project is runnung. you can access it directly : Process.Start("regedit.exe", "/s " + "Filename.reg");
you can get the current path by using
string path =System.AppDomain.CurrentDomain.BaseDirectory; // this will give u the path for debug folder
or
string projectPath= Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())); //This will give u the project path.
you can use both and navigate arround to get the path to your desired folder. eg if you want to access a file in the Resource folder inside the project folder u can use projectPath+"\\Resource\\filename.reg"
If the file is embedded resource (and as such is not created on disk), it is best to read it like this and save it to a temporary file using:
var path = System.IO.Path.ChangeExtension(System.IO.Path.GetTempFileName(), "reg");
Process.Start(path);
It may not be necessary to change the extension if you don't start the file directly but use Process.Start("regedit", "/s " + path) like you described in your question. Keep in mind that the file path should be escaped so it's parsed properly as the command line argument, temporary file path, though, will not contain spaces, so it should be okay.
This is not tested code, but you get the steps I hope:
Process proc = new Process();
proc.StartInfo.FileName = "regedit.exe";
proc.StartInfo.Arguments = "/s";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.Start();
StreamWriter stdin = myProcess.StandardInput;
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "<regfile>";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
stdin.Write(reader.ReadToEnd());
}

Copy a file with its original permissions

When using the File.Copy() method the file is copied to its new directory however it loses its original permissions.
Is there a way to copy a file so that it doesn't lose the permissions?
I believe you can do something like this:
const string sourcePath = #"c:\test.txt";
const string destinationPath = #"c:\test2.txt"
File.Copy(sourcePath, destinationPath);
FileInfo sourceFileInfo = new FileInfo(sourcePath);
FileInfo destinationFileInfo = new FileInfo(destinationPath);
FileSecurity sourceFileSecurity = sourceFileInfo.GetAccessControl();
sourceFileSecurity.SetAccessRuleProtection(true, true);
destinationFileInfo.SetAccessControl(sourceFileSecurity);
Alex's answer, updated for .NET Core 3.1 (actually most .NET):
var sourceFileInfo = new FileInfo(sourcePath);
var destinationFileInfo = new FileInfo(destinationPath);
// Copy the file
sourceFileInfo.CopyTo(destinationPath, true); // allow overwrite of the destination
// Update the file attributes
destinationFileInfo.Attributes = sourceFileInfo.Attributes

Categories

Resources