when i run file.copy to copy files in network path for large files i get the below error but in back end files are getting copied twice.
This site can’t be reached The webpage at http://******************* might be temporarily down or it may have moved permanently to a new web address. ERR_INVALID_HANDLE
foreach (GridViewRow row in grdAppDetails.Rows)
{
Label lblPublishPath = (Label)row.FindControl("lblPublishPath");
Label lblBackupPath = (Label)row.FindControl("lblBackupPath");
string BackupPath = lblBackupPath.Text + "\\" + drpApplication.SelectedValue.ToString() + "_" + DateTime.Now.ToString("yyyyMMdd");
DirectoryCopy(lblPublishPath.Text, BackupPath, true);
DirectoryCopy(txtFolderUpload.Text, lblPublishPath.Text, true);
deploymentdata.AddAppLogDetails(drpApplication.SelectedValue.ToString(), drpEnv.SelectedValue.ToString(), lblUserName.Text, DateTime.Now, txtFolderUpload.Text, BackupPath, lblPublishPath.Text, txtComments.Text, filenames);
}
try to :
1- ping the destination to be sure that you have access.
2- once the ping succeed , try to check if you can write file from your machine
you can do it like this : Properties-->share --> and add your user if you don't have access to the directory
Related
I've created a backup and restore procedure for my application. When the backup is run, it will create a .zip file of the SQLite database in the same directory as the database.
When restoring the database, it will rename the database, changing it from EPOSDatabase.db3 to tempEPOS.db3
Then, it takes the selected file and extracts it to the same location, under the name EPOSDatabase.db3, before deleting the renamed temporary database.
string dbPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
if (File.Exists(dbPath + "/tempEPOS.db3"))
{
File.Delete(dbPath + "/tempEPOS.db3");
};
File.Move(dbPath + "/EPOSDatabase.db3", dbPath + "/tempEPOS.db3");
ZipFile.ExtractToDirectory(dbPath + "/" + fileToRestore, dbPath + "/EPOSDatabase.db3");
File.Delete(dbPath + "/tempEPOS.db3");
My issue is that when I then have code that opens the connection, for example when I open the system settings page after the restore has been carried out, I get an error:
"Could not open database file: /data/user/0/com.companyname.ACPlus_MobileEPOS/files/EPOSDatabase.db3 (CannotOpen)"
As a further debug test, I added this code to the startup of the application:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
foreach (var file in Directory.GetFiles(path))
{
string strFile = Convert.ToString(file);
}
public readonly string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "EPOSDatabase.db3");
var db = new SQLiteConnection(dbPath);
db.CreateTable<Category>();
db.CreateTable<SystemSettings>();
db.Close();
In the foreach loop, it only found the original .zip file that I was trying to restore from.
Then when it reaches the line
var db = new SQLiteConnection(dbPath);
it fails to create the database with the message
"Could not open database file: /data/user/0/com.companyname.ACPlus_MobileEPOS/files/EPOSDatabase.db3"
It seems like the file doesn't exist, so hasn't extracted properly, but if that was the case then why does it not just create a new database, rather than try to open it?
The extraction logic needs to be rechecked.
Specifically ExtractToDirectory.
Extracts all the files in the specified zip archive to a directory on the file system.
public static void ExtractToDirectory (string sourceArchiveFileName, string destinationDirectoryName);
In the original code
ZipFile.ExtractToDirectory(dbPath + "/" + fileToRestore, dbPath + "/EPOSDatabase.db3");
The contents of the zip file are extracting to a directory called {path}/EPOSDatabase.db3/.
If the goal was just to extract from the archive to the directory then only the directory location is required.
ZipFile.ExtractToDirectory(dbPath + "/" + fileToRestore, dbPath);
Additionally, a check should be done to make sure the desired file actually exists after the restore before deleting the old file.
//... extraction code omitted for brevity
if (!File.Exists(dbPath + "/EPOSDatabase.db3")) {
//...either throw error or alert that database is not present
//...could consider return old file back to original sate (optional)
} else {
File.Delete(dbPath + "/tempEPOS.db3");
}
I have an ASP.NET MVC application, hosted on IIS 8, windows server 2012 and I upload some files to a temporary directory. After doing some other work, all these files are moved to a concrete directory. My question is why doesn't Directory.Move work while FileInfo.CopyTo works.
Directory.Move fails with
"Access to the path 'serverPath...' is denied."
Code I'm using to move entire directory:
var pathFrom = Server.MapPath("~/Uploads/Objects/" + tempFolderName); //tempFolderName is a random generated GUID.
var pathTo = Server.MapPath("~/Uploads/Objects/" + ObjectId); //ObjectId is an integer
if (Directory.Exists(pathFrom))
{
Directory.Move(pathFrom, pathTo);
}
To create a temporary directory I'm simply calling: Directory.CreateDirectory(path) which works and creates the temporary directory, and files are saved inside it.
Method I use to copy files, one by one, which works:
public static void DirectoryCopy(string strSource, string Copy_dest)
{
DirectoryInfo dirInfo = new DirectoryInfo(strSource);
DirectoryInfo[] directories = dirInfo.GetDirectories();
FileInfo[] files = dirInfo.GetFiles();
foreach (DirectoryInfo tempdir in directories)
{
Console.WriteLine(strSource + "/" + tempdir);
Directory.CreateDirectory(Copy_dest + "/" + tempdir.Name);// creating the Directory
var ext = System.IO.Path.GetExtension(tempdir.Name);
if (System.IO.Path.HasExtension(ext))
{
foreach (FileInfo tempfile in files)
{
tempfile.CopyTo(Path.Combine(strSource + "/" + tempfile.Name, Copy_dest + "/" + tempfile.Name));
}
}
DirectoryCopy(strSource + "/" + tempdir.Name, Copy_dest + "/" + tempdir.Name);
}
FileInfo[] files1 = dirInfo.GetFiles();
foreach (FileInfo tempfile in files1)
{
tempfile.CopyTo(Path.Combine(Copy_dest, tempfile.Name));
}
}
What I tried to make Directory.Move work:
Checked to see if directory pathTo doesn't exist
Checked to see if IIS has required permissions: IISAppPool/DefaultAppPool has full access to the Uploads folder.
Tried to check with Process monitor if any other error comes up but it seems that this doesn't even get logged.
Closed every explorer.
Can anyone explain why Directory.Move doesn't work (with the access deny error) while moving the files one by one works?
Does Directory.Move require more privileges than just copying files 1 by 1?
Please be aware that the application is not under wwwroot... but on other drive.
Pages I already read:
Why am I still getting "Access to the path 'C:\...\...' is denied" even after granting IIS_IUSRS write permission on the directory?
Access to path denied on IIS
IOException access denied when Directory.Move subfolder and parent folder
EDIT
After copying the files using FileInfo.Copy I delete the tempFolder with Directory.Delete(pathFrom, true); which also works.
I am moving files from source folder to destination folder. Before moving files, I am checking that directory exists or not which is working fine. The issue is with my second check where I want to make sure that folder is not empty before moving files but it is not giving me correct result.
public void MoveFilesFromTempToSourceTbl()
{
//Moving all files from temp folder to orig folder.
string sourceFolder = (twitterDO.Path + "\\" + msgDate.Year.ToString() + "\\" + msgDate.Month.ToString() + "\\" + msgDate.Day.ToString() + "_Temp").Replace("\\", #"\");
string destinationFolder = (twitterDO.Path + "\\" + msgDate.Year.ToString() + "\\" + msgDate.Month.ToString() + "\\" + msgDate.Day.ToString()).Replace("\\", #"\");
string pattern = "*.txt";
if (Directory.Exists(sourceFolder))
{
if (File.Exists(pattern))
{
foreach (var file in new DirectoryInfo(sourceFolder).GetFiles(pattern))
{
file.MoveTo(Path.Combine(destinationFolder, file.Name));
}
}
if (Directory.GetFiles(sourceFolder).Length == 0) //Before deleting make sure that Temp folder is empty.
Directory.Delete(sourceFolder, true); // Delete Temp folder after moving all the contents.
}
}
I know I am making some small mistake but not sure what it is. Following is the screenshot of the result which I got in immediate window.
http://imgur.com/FZvo9cj
There's a bit of redundancy in your current code. Starting with the if-checks, here's how I would approach this:
var sourceDirectory = new DirectoryInfo(sourceFolder); // remember this, it is reused
if (sourceDirectory.Exists)
{
// Look for the files in the directory, if none found, will be empty array
foreach (var file in sourceDirectory.GetFiles(pattern))
{
file.MoveTo(Path.Combine(destinationFolder, file.Name));
}
// Re-check the directory for any remaining files
if (sourceDirectory.GetFiles(pattern).Length == 0) //Before deleting make sure that Temp folder is empty.
sourceDirectory.Delete(); // Delete Temp folder after moving all the contents.
}
As a small performance improvement, you could replace sourceDirectory.GetFiles() with sourceDirectory.EnumerateFiles() in the for-loop. This will allow you to start moving them as the method finds them, not after they have all been found.
You are passing "*.txt" into the File.Exists() call when you need to be passing a path.
You can read the Documentation here
Alternatively you could use something like this:
Directory.GetFiles(destinationFolder).Contains(filename)
I agree with David here but also I think the flow of you logic should be adjusted a bit. The File.Exixts(filename); should occur inside the foreach.
That will allow you to iterate each file and if it exists do something.
Try adding the following to check if any files exist in the location:
bool exist = Directory.EnumerateFiles(sourceFolder, "*.txt").Any();
I'm currently developing a website using asp and c#. One of the pages allows registered users to upload files. These files get stored according to the user who is logged in. A directory is created when they hit upload with there login name and id.
string userDirectory = "\\Test\\Files\\ " + User.Identity.Name + " " + User.Identity.GetUserId();
if (!Directory.Exists(userDirectory))
{
Directory.CreateDirectory(userDirectory);
}
The directory gets created without an issue and file also gets uploaded. However the problem I am now facing is I'm trying to add a date stamp to a file if it already exist in the directory so I don't overwrite it. See the code below
string fileName = Path.Combine(userDirectory, FileUpload1.FileName);
if (!File.Exists(fileName))
{
FileUpload1.SaveAs(fileName);
}
else
{
fileName = string.Concat(
Path.GetFileNameWithoutExtension(fileName),
DateTime.Now.ToString("_yyyy_MM_dd_HH:mm:ss"),
Path.GetExtension(fileName)
);
FileUpload1.SaveAs(fileName);
}
This keeps giving me an error:
System.Web.HttpException: The SaveAs method is configured to require a rooted path, and the path 'Test.docx' is not rooted
Does anyone know where I'm going wrong? Thanks in advance
You have to append the directory name to the path, since you stripped it off (by using GetFileNameWithoutExtension):
string newFileName =
Path.Combine( Path.GetDirectoryName(fileName)
, string.Concat( Path.GetFileNameWithoutExtension(fileName)
, DateTime.Now.ToString("_yyyy_MM_dd_HH_mm_ss")
, Path.GetExtension(fileName)
)
);
Also note that using : in a file name is not supported, so I replace it with _.
I have a return a c# code to save a file in the server folder and to retrieve the saved file from the location. But this code is working fine in local machine. But after hosting the application in IIS, I can save the file in the desired location. But I can't retrieve the file from that location using
Process.Start
What would be the problem? I have searched in google and i came to know it may be due to access rights. But I don't know what would be exact problem and how to solve this? Any one please help me about how to solve this problem?
To Save the file:
string hfBrowsePath = fuplGridDocs.PostedFile.FileName;
if (hfBrowsePath != string.Empty)
{
string destfile = string.Empty;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\\\";
if (!Directory.Exists(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)))
Directory.CreateDirectory(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1));
FileInfo FP = new FileInfo(hfBrowsePath);
if (hfFileNameAutoGen.Value != string.Empty)
{
string[] folderfiles = Directory.GetFiles(FilePath);
foreach (string fi in folderfiles)
File.Delete(fi);
//File.Delete(FilePath + hfFileNameAutoGen.Value);
}
hfFileNameAutoGen.Value = PONumber + FP.Extension;
destfile = FilePath + hfFileNameAutoGen.Value;
//File.Copy(hfBrowsePath, destfile, true);
fuplGridDocs.PostedFile.SaveAs(destfile);
}
To retrieve the file:
String filename = lnkFileName.Text;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\";
FileInfo fileToDownload = new FileInfo(FilePath + "\\" + filename);
if (fileToDownload.Exists)
Process.Start(fileToDownload.FullName);
It looks like folder security issue. The folder in which you are storing the files, Users group must have Modify access. Basically there is user(not sure but it is IIS_WPG) under which IIS Process run, that user belongs to Users group, this user must have Modify access on the folder where you are doing read writes.
Suggestions
Use Path.Combine to create folder or file path.
You can use String.Format to create strings.
Create local variables if you have same expression repeating itself like FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)
Hope this works for you.
You may have to give permissions to the application pool that you are running. see this link http://learn.iis.net/page.aspx/624/application-pool-identities/
You can also use one of the built-in account's "LocalSystem" as application pool identity but it has some security issue's.