I am trying to use the code below to allow all users be able to modify a folder:
class Program
{
private const string FileName = "test.txt";
private static readonly string FilePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\TEST\\" + FileName;
private static readonly string UserName = Environment.UserDomainName;
static void Main()
{
DirectorySecurity securityRules = new DirectorySecurity();
string dirPath = Path.GetDirectoryName(FilePath);
securityRules.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.Modify, AccessControlType.Allow));
if (dirPath == null) throw new InvalidOperationException("Failure to save local security settings");
if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath, securityRules);
File.WriteAllText(FilePath, "Test test!");
}
}
After I run the code, the Users is added to the folder, but not with any rights assigned. All the read, write, execute etc. all the check boxes are not checked. Except the Special permissions is checked.
How Can I add a folder with all Modify for all users?
You can use the Directory.SetAccessControl().
Example:
DirectoryInfo directory = new DirectoryInfo(#"C:\my\directory");
DirectorySecurity security = directory.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(#"MYDOMAIN\JohnDoe",
FileSystemRights.Modify,
AccessControlType.Deny));
directory.SetAccessControl(security);
More details in the msdn.
Related
I got a folder in C called "donotcopy". I want to protect it and no matter what not to be allowed to create files within.
My intuitive solution was just to create a str with same name and where user enters a destination it just checks if it's the same.
Example:
class FileCreation
{
public static void Main()
{
string notallowed = ("c:\\donotcopy");
string filename = ("Nick.txt");
Console.WriteLine("Enter the full path to create an empty file.");
string path = Console.ReadLine();
path = path.ToLower();
while (notallowed == path)
{
Console.WriteLine("The chosen path is not allowed please try another one.");
path = Console.ReadLine();
path = path.ToLower();
}
using (FileStream fs = File.Create(path + filename)) ;
}
}
The problem is if the user enters the destination as "c:.\donotcopy" it will still create the file inside the restricted folder.
You can make use of the DirectoryInfo class, which will allow you to retrieve info about the full path of a directory.
class FileCreation
{
public static void Main()
{
string notallowed = ("c:\\donotcopy");
string filename = ("Nick.txt");
Console.WriteLine("Enter the full path to create an empty file.");
DirectoryInfo directory = new DirectoryInfo(Console.ReadLine());
while (notallowed.Equals(directory.FullName, StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("The chosen path is not allowed please try another one.");
directory = new DirectoryInfo(Console.ReadLine());
}
string fullPath = Path.Combine(directory.FullName, filename);
using (FileStream fs = File.Create(fullPath)) ;
}
}
I have a folder full of text files. I want to zip each one individually. If there are First.txt and Second.txt in the folder C:\Temp\raw
I want to zip First.txt as First.zip and move it to C:\Temp\Done and Second.txt zipped as Second.zip and move it to C:\Temp\Done. This is the code I have
-- SourcePath = C:\Temp\raw tempPath = C:\temp\Done in app.config
public static DirectoryInfo sourcePath = new DirectoryInfo(ConfigurationManager.AppSettings["sourcePath"].ToString());
public static string tempPath = ConfigurationManager.AppSettings["tempPath"].ToString();
var files = System.IO.Directory.GetFiles(sourcePath.ToString(), "*.txt").OrderBy(f => f);
string zipfilename = "";
try
{
foreach (var fPath in files)
{
string fileNameNoPath = Path.GetFileName(fPath);
string destFile = Path.Combine(tempPath, fileNameNoPath);
System.IO.File.Move(fPath, destFile);
ZipFile.CreateFromDirectory(tempPath, tempPath, CompressionLevel.Fastest, true);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
I am getting errors. System.UnauthorizedAccessException: Access to the path 'C:\Temp\Done' is denied
I do have access to C:\temp\folder and I am running as admin
Can someone guide me
Thanks
MR
enter image description here
I am creating a dynamic folder as seen in the design in the image. I need to download two file types of data in a link to this folder I created, but how can I download it to the folder I created?
klasor = textBox1.Text;
var yol = Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + #"Beyza\source\" + klasor);
In this way, I create a folder in the 'klasor' variable.
public void indirButon_Click(object sender, EventArgs e)
{
string fileName = "C:\\Users\\Hilal Beyza\\Desktop\\projeler\\LinkProgram\\LinkProgram\\bin\\Debug\\Hilal Beyza\\yol\\webcams.mp4";
WebClient web = new WebClient();
web.DownloadFileCompleted += new AsyncCompletedEventHandler(Dosyaİndirme);
Uri DosyaAdresi = new Uri(label3.Text);
web.DownloadFile(DosyaAdresi, fileName);
}
I am giving my downloaded file a static path as above. How can I transfer this to the file I created?
Recommendations: When you write a program try to name components with a logic name, example txtUri, txtFolderName, btnDownload, this facilitates understanding.
If you have a File Name and Dynamic Folder it's possible.
public void indirButon_Click(object sender, EventArgs e)
{
string fileName = GetFileName("webcams.mp4");
WebClient web = new WebClient();
web.DownloadFileCompleted += new AsyncCompletedEventHandler(DosyaIndirme);
Uri DosyaAdresi = new Uri(label3.Text);
web.DownloadFile(DosyaAdresi, fileName);
}
This method Get File Name with new Dynamicly Folder.
private static string GetFileName(string fileName)
{
string klasor = textBox1.Text;
string directoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Hilal Beyza\source\", klasor);
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
return Path.Combine(directoryPath, fileName);
}
If User pass complete path you need remove adapt the directoryPath
string directoryPath = Path.Combine(textBox1.Text);
I want create directory with Active directory user credentials, only that user has access for directory manipulation like opening listing files, reading files etc.
public void CreateDirectory(int value)
{
string drive = Directory.GetDirectoryRoot(HostingEnvironment.ApplicationPhysicalPath);
string path = "D://" + "4524l";
DirectoryInfo dinfo = Directory.CreateDirectory(path);
string domainAndUsername = "456456.com" + #"\" + "guserone";
DirectoryEntry entry = new DirectoryEntry("LDAP://124.com", domainAndUsername, "a55in123*");
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + "guserone" + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
DirectorySecurity myDirectorySecurity = dinfo.GetAccessControl();
//myDirectorySecurity.SetOwner(newUser);
myDirectorySecurity = RemoveExplicitSecurity(myDirectorySecurity);
dinfo.SetAccessControl(myDirectorySecurity);
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(domainAndUsername,
FileSystemRights.FullControl, AccessControlType.Allow));
dinfo.SetAccessControl(myDirectorySecurity);
myDirectorySecurity.SetAccessRuleProtection(true, false);
}
private static DirectorySecurity RemoveExplicitSecurity(DirectorySecurity directorySecurity)
{
AuthorizationRuleCollection rules = directorySecurity.GetAccessRules(true, false, typeof(System.Security.Principal.NTAccount));
foreach (FileSystemAccessRule rule in rules)
directorySecurity.RemoveAccessRule(rule);
return directorySecurity;
}
Assuming you are dealing with a simple scenario, you are probably looking for Directory.CreateDirectory(string path, DirectorySecurity directorySecurity), which you can find documented here.
There's a decent example there that includes creation of basic access controls.
When I use this code it doesn't throw any errors but it still doesn't copy anything. Any ideas?.
//string spath = string.Format("S:\\ 0A36303 / user:admin");
DateTime theDate = dateTimePicker1.Value.Date;
DirectoryInfo Dir = new DirectoryInfo("S:");
string dircreate = string.Format(#"N:\{0:MM-dd-yyyy}\" + label1.Text + "LogFiles", dateTimePicker1.Value.Date, label1.Text);
DirectoryInfo target = new DirectoryInfo(dircreate);
FileInfo[] fis = Dir.GetFiles( ".txt", SearchOption.AllDirectories);
foreach (FileInfo fi in fis)
{
if (fi.LastWriteTime.Date == theDate)
{
File.Copy(fi.FullName, target.FullName + #"\" + fi.Name, true);
}
}
}
}
}
Try using the full UNC path to access the file:
DirectoryInfo Dir = new DirectoryInfo(#"\\server\\share\\pathtofile");
Two possible problems come to mind:
The S:\PC.log file doesn't exist => you cannot copy non-existent file
The process you are executing your code under doesn't have read permission to the specified folder (S:). Looks like a network share. If you are running this code inside an ASP.NET application the process probably doesn't have read permissions to this remote share => you cannot copy a file that you don't have permissions to access.