System.UnauthorizedAccessException: Access to the path C - c#

I am trying to build a automatic backup and restore system.
My logfile:
2012-08-02 22:34:06 - Init: Folder main created for server Teamdeathmatch
2012-08-02 22:34:06 - Backup: Couldn't copy files: System.UnauthorizedAccessException: Access to the path 'C:/temp/backups/Teamdeathmatch/server/main' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite)
at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite)
at BackupRollback.Backup.getServerFiles() in C:\Users\jordi\Desktop\ConsoleApplication1 - kopie\Backup.cs:line 51
The target and the file exist.
I hope that anyone can help me. Also some feedback about my programming of c# since c-sharp is new for me.
Thank you
class Backup
{
public static void getServerFiles()
{
Log.Info("Get servers");
string[] fileEntries = Directory.GetDirectories("c:/Gameservers");
Log.Info("Servers found: " + fileEntries.Count());
string _directoryPath = #"C:\temp\backups";
// check folder exists
if (!Directory.Exists(_directoryPath))
{
Log.Data("Temp backup folder not found");
Directory.CreateDirectory(_directoryPath);
Log.Data("Temp backup folder created successfully");
}
else
{
Log.Data("Temp backup folder found");
}
// move files to directory
foreach (string fileName in fileEntries)
{
try
{
string servername = Path.GetFileNameWithoutExtension(fileName);
Directory.CreateDirectory("C:/temp/backups/" + servername + "/server");
Log.Data("Folder server created for server " + servername);
Directory.CreateDirectory("C:/temp/backups/" + servername + "/server/main");
Log.Data("Folder main created for server " + servername);
File.Copy("C:/temp/backups/" + servername + "/server/main", "C:/Gameservers/" + servername + "/server/main/server.cfg");
Log.Data("File server.cfg copied for server " + servername);
Directory.CreateDirectory("C:/temp/backups/" + servername + "/b3 server/conf");
Log.Data("Folder conf [b3] created for server " + servername);
File.Copy("C:/temp/backups/" + servername + "/server/main", "C:/Gameservers/" + servername + "/b3 server/conf/b3.xml");
Log.Data("File b3.xml copied for server " + servername);
Directory.CreateDirectory("C:/temp/backups/" + servername + "/server/mods");
Log.Data("Folder mods created for server " + servername);
DirectoryCopy("C:/temp/backups/" + servername + "/server/", "C:/Gameservers/mods/" + servername + "/server/mods/");
Log.Data("Folder mods copied for server " + servername);
}
catch (Exception ex)
{
Log.Data("Couldn't copy files: " + ex.ToString());
}
}
}
private static void DirectoryCopy(string sourceDirName, string destDirName)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath);
}
}
}

File.Copy(source, destination)
You have your parameters reversed. Try this instead.
File.Copy"C:/Gameservers/" + servername + "/server/main/server.cfg",
"C:/temp/backups/" + servername + "/server/main");
Log.Data("File server.cfg copied for server " + servername);

Related

Error with database file path in project with many databases

I have an error with database file path, the project has many databases with 10 tables, for each file should have 1 database, I create a database but it can't be saved as file ... and the error is:
The File Path Is Not Supported ...
public class filewrite
{
public string datadress, dataname, databaseadress, tablexist, dsname, databak, dataldf, databakldf, filepath, filename;
public filewrite()
{
databaseadress = "baseadress";
dataname = "name";
datadress = "adress";
dsname = "databasename1";
databak = "backUp";
tablexist = "yesorno";
dataldf = "dl";
databakldf = "dbl";
filepath = "path";
filename = "name";
}
public byte writing()
{
if (File.Exists(filepath + #"\" + filename + #"\Data" + datadress))
File.Delete(filepath + #"\" + filename + #"\Data" + datadress);
if (File.Exists(#"C:\tempFile.SMP"))
File.Delete(#"C:\tempFile.SMP");
string path = filepath + #"\" + filename + #"\Data" + datadress;
FileStream fpath = File.Create(path);(The error is in here)
try
{
// read from file or write to file
StreamWriter fwrite = new StreamWriter(fpath);
fwrite.WriteLine(datadress);
fwrite.WriteLine(dataname);
fwrite.WriteLine(databaseadress);
fwrite.WriteLine(tablexist);
fwrite.WriteLine(dsname);
fwrite.WriteLine(databak);
fwrite.WriteLine(dataldf);
fwrite.WriteLine(databakldf);
fwrite.Close();
}
finally
{
}
File.Copy(filepath + #"\" + filename + #"\Data" + datadress, #"C:\tempFile.SMP");
return 10;
}
}
Rather than using filepath + #"\" + filename + #"\Data" + datadress;,
Try using System.IO.Path.Combine instead:
Path.Combine(filepath, fileName, Data, datadress);
which returns a string.

Listing all the files in root directory

Thanks for your support! I now have working code to scan all folders, subfolders and files. There is just one problem left to solve:
I do not get the files in the initial root directory, only the subfolders. I also need to call FileInfo for these files.
How could this be resolved without modifying the code too much?
private void ScanFolder(String prefix, String path)
{
try
{
string user = System.IO.File.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
DirectoryInfo di = new DirectoryInfo(path);
foreach (var dir in new DirectoryInfo(path).GetDirectories("*", SearchOption.TopDirectoryOnly))
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + dir.Name + " (" + dir.Name.Length.ToString() + ") "); });
foreach (FileInfo fileInfo in dir.GetFiles())
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + fileInfo.Name + " (" + fileInfo.Name.Length.ToString() + ") " + user + " " + fileInfo.FullName + " (" + fileInfo.FullName.Length.ToString() + ")"); });
}
ScanFolder(prefix + "—", dir.FullName);
}
}
catch
{
if (!this.IsDisposed)
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + path); });
}
}
}
Output:
** The files should be here **
13-9-legacy_vista_win7_64_dd_ccc_whql (37)
Radeon-Software-Adrenalin-18.3.3-MinimalSetup-180319_web (56)
—Bin (3)
——localization (12)
———cs (2)
———da_DK (5)
———de (2)
———el_GR (5)
———es_ES (5)
So far you're only looking for the directories in the root directory.
You also want to enumerate through the files though:
private void ScanFolder(String prefix, String path)
{
try
{
string user = System.IO.File.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
DirectoryInfo di = new DirectoryInfo(path);
// Enumerate through the files here
foreach (FileInfo fileInfo in di.GetFiles())
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + fileInfo.Name + " (" + fileInfo.Name.Length.ToString() + ") " + user + " " + fileInfo.FullName + " (" + fileInfo.FullName.Length.ToString() + ")"); });
}
// ----
// You can also use the DirectoryInfo you created earlier here
foreach (var dir in new di.GetDirectories("*", SearchOption.TopDirectoryOnly))
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + dir.Name + " (" + dir.Name.Length.ToString() + ") "); });
foreach (FileInfo fileInfo in dir.GetFiles())
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + fileInfo.Name + " (" + fileInfo.Name.Length.ToString() + ") " + user + " " + fileInfo.FullName + " (" + fileInfo.FullName.Length.ToString() + ")"); });
}
ScanFolder(prefix + "—", dir.FullName);
}
}
catch
{
if (!this.IsDisposed)
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + path); });
}
}
}

Problems in accessing server for file in asp.net c#?

I am trying to connect to a remote server and access a specific directory in that server for searching a file but for some reason it shows that the directory doesnt exist on the server even though it actually exists. I am guessing that my file path is wrong. Can anyone please suggest me if I made a syntax error?
filepath = #"\\172.17.20.11\E$\MessageLogs\" + logType + "\\" + country + "\\" + year + "\\" + month + "\\" + day + "\\";
private void GetFiles(string filePath)
{
try
{
tblFileContent = new DataTable();
getColumns(tblFileContent);
//C:\MessageLogs\ElmaCore\KENYA\2016\March\22
//filePath = #"C:\MessageLogs\"+filePath; //Pick a folder on your machine to store the uploaded files
if (!Directory.Exists(filePath))
{
fn.MessageLine(this.Page, "Log folder does not exist.", System.Drawing.Color.Red, "lblMessageLine");
dtDate.Focus();
return;
}
string searchReference = txtReference.Text.Trim();
//string filePath = System.Configuration.ConfigurationManager.AppSettings["InFolder"].ToString();
DirectoryInfo DirInfo = new DirectoryInfo(filePath);
FileInfo[] CsvFiles = DirInfo.GetFiles("*" + searchReference + "*.log").OrderByDescending(p => p.LastWriteTime).ToArray();
if (CsvFiles.Length > 0)
{
foreach (var file in CsvFiles)
{
string FileName = file.Name;
string sourceFile = System.IO.Path.Combine(filePath, FileName);
ProcessFile(FileName, sourceFile);
}
//LoadGrid();
}
else {
fn.MessageLine(this.Page, "Sorry, No files found for the specified reference.", System.Drawing.Color.Red, "lblMessageLine");
txtReference.Focus();
return;
}
}
catch (Exception ex)
{
fn.MessageLine(this.Page, "Sorry an Error Occured. Please try again", System.Drawing.Color.Red, "lblMessageLine");
ErrLogger.LogError("filelog-" + ex.Message); //oledbconn.Close();
return;
}
}
As you say your directory exists than it might the problem with permission.
Please make sure account under which code is been running have permission to that folder.
Also note that once you deploy in IIS, change identity of apppool to a domain user who has permission.
If you want to verify if its permission problem, than just do this.
Right click into that folder and give permission to everyone and test.

IOException when moving an image file

private void MoveFile(string destination, string imagePath)
{
try
{
string source = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["TempImagePath"]);
string[] resizedImage = imagePath.Split('.');
//string compressedImagePath = resizedImage[0] + "_compress." + resizedImage[1];
string thumbnail150Name = resizedImage[0] + "_thumbnail." + resizedImage[1];
string mediumPhoto300Name = resizedImage[0] + "_mediumPhoto." + resizedImage[1];
string largePhotoName = resizedImage[0] + "_largePhoto." + resizedImage[1];
//Move thumbnail
if (System.IO.File.Exists(source + "\\" + thumbnail150Name))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + thumbnail150Name, destination + "\\" + thumbnail150Name);
}
//Move medium sized photo
if (System.IO.File.Exists(source + "\\" + mediumPhoto300Name))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + mediumPhoto300Name, destination + "\\" + mediumPhoto300Name);
}
//Move large photo
if (System.IO.File.Exists(source + "\\" + largePhotoName))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + largePhotoName, destination + "\\" + largePhotoName);
}
//Move original
if (System.IO.File.Exists(source + "\\" + imagePath))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + imagePath, destination + "\\" + imagePath);
}
}
catch (Exception ex)
{
BgLogger.FileLogger.LogError("In private method : MoveFile(string, string), On server : " + Dns.GetHostName() + " At : " + DateTime.Now, ex).Wait();
}
}
I am using this code while moving an image file. But I am getting the following exception
System.IO.IOException: The process cannot access the file because it
is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalMove(String sourceFileName, String
destFileName, Boolean checkHost) at
BgPortal.Controllers.DriverController.MoveFile(String destination,
String imagePath)
https://u3307993.ct.sendgrid.net/wf/open?upn=mzyvlCvUM5odb-2FP3IS9fxavC9Nq-2BVU-2BlgxLxmreq6Qi5SziY4JAfC5R720TrBfTXj7GdvSOgEG2Qeq-2BGKm-2FwWmPOrbAem6UFnvcBKca-2FzIM3XkXg0dHdke9rhjcAKDqtd0MJQCnmyIN-2Fi-2FXbgygtnXFNxuEuwts4hybPsnVR72PsfW4L6YZ32pnlEuwGMF-2Fcg0S8f8Y7UOBHwDMzh1BgJnhqO9i5dgS9LRZytY4n6TNCt37JAtdi5EOj8OxBqhan
This exception occurs very randomly.
Can anyone help me with this?
The exception is thrown because the file you are trying to move is open by your program or another process. Make sure that you are always closing the file after you finish processing it. Particularly, make sure that you always call Close or Dispose on all FileStream objects when they are no longer needed.
If the file is open by another process (for example by another user) then you can wait for some time and retry moving the file.

listing virtual directories permissions

So I ran across this article for listing out virtual directories. And the article shows how I can specify a username and password for DirectoryEntry. But I'm still getting Access is denied.
There is still something I'm not grasping about permissions. Any ideas?
class Program
{
static void Main(string[] args)
{
//http://www.developmentnow.com/blog/2004/12/29/recursively-list-virtual-directories-in-iis-with-c-and-directoryservices/
// call the function once to kick it off
WriteVDirs("localhost", 2, "");
}
// function that recursively walks through IIS dir & vdirs & lists all the virtual directories
public static void WriteVDirs(string serverName, int SiteNumber, string path)
{
DirectoryEntry de =
new DirectoryEntry("IIS://" + serverName + "/W3SVC/" +
SiteNumber.ToString() + "/Root" + path);
de.Username = "my-machine/administrator";
de.Password = "admin";
DirectoryEntries dirs;
try
{
dirs = de.Children;
foreach (DirectoryEntry d in dirs)
{
if (0 == String.Compare(d.SchemaClassName, "IIsWebDirectory"))
{
string fullPath = path + "/" + d.Name;
WriteVDirs(serverName, SiteNumber, fullPath);
}
else if (0 == String.Compare(d.SchemaClassName, "IIsWebVirtualDir"))
{
string fullPath = path + "/" + d.Name;
Console.WriteLine(fullPath + " : " + d.Properties["Path"].Value);
WriteVDirs(serverName, SiteNumber, fullPath);
}
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR: " + ex.Message);
}
}
}

Categories