Copy a file with its original permissions - c#

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

Related

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

Copy files from one path to another path in 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);

Saving files and listing them in default directory

When I want to save a file I use:
FileStream fs = new FileStream(fileName + ".asdf", FileMode.OpenOrCreateOrReadOrBlah);
which will save the file in:
C:\Users\ME\Documents\Visual Studio 2010\Projects\Project A\Project A\Project A\bin\x86\Debug
which is fine
but how do i list the files in that particular folder?
it will be different for every computer
List<string> fileNames = new List<string>();
DirectoryInfo di = new DirectoryInfo(****What goes here?****);
FileInfo[] rgFiles = di.GetFiles("*.asdf");
foreach (FileInfo fi in rgFiles)
{
fileNames.Add(fi.Name);
}
Thanks!
In your save, you are not specifying a directory, so it defaults to the current directory.
var di = new DirectoryInfo(Directory.GetCurrentDirectory());
First off, when you save a file without a path, it goes into the current working directory, not necessarily Debug.
Secondly, you can get the current working directory with:
string currentPath = Environment.CurrentDirectory;
DirectoryInfo di = new DirectoryInfo(****What goes here?****);
"Here" is where the directory name which you want to manipulate would go.

How to modify the attributes of a file with no extension in C#?

This is my code
static string pat = "C:\\" + System.Environment.UserName +
"\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History";
FileInfo hist = new FileInfo(pat);
Here History is a file, with no extension.
All I want to do is this:
hist.IsReadOnly = true;
But directorynotfoundexception comes. Please help me, how do I access the file, it thinks that History is a directory!
Your path is strange. It starts like "C:\Username\AppData...".
I think what you are looking for is something like this:
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
path = System.IO.Path.Combine(path, "Google\\Chrome\\User Data\\Default\\History");
The result will look like this (on XP):
C:\Documents and
Settings\Username\Local
Settings\Application
Data\Google\Chrome\User
Data\Default\History
Windows 7 will give you different result.
This has to work for file with or without extension:
FileInfo fi = new FileInfo(path);
fi.Attributes |= System.IO.FileAttributes.ReadOnly;
And this has to work for directory:
DirectoryInfo di = new DirectoryInfo(path);
di.Attributes |= System.IO.FileAttributes.ReadOnly;
I think your directory is wrong, you seem to be missing the 'Users' folder. It should be:
static string pat = "C:\\Users\\" + System.Environment.UserName + ...

Categories

Resources