string path = Path.GetDirectoryName(Application.ExecutablePath) +
"\\" + directores[directores.Length - 2] +
"\\" + Path.GetFileName(url_img).Replace(" ", "_");
client.DownloadFileAsync(new Uri(url_img), path);
This code over doesn't work, the path seems to be good when i check it via MessageBox:
I have tried also with # symbol, but it neither works.
If I enter not a path but a name, e.g
client.DownloadFileAsync(new Uri(url_img), "test");
everything is ok. How can I solve this?
Forgot to add: If such path doesn't exist, I want to create it!
Whenever using async methods is your responsibility to check the result. For DownloadFileAsync the responsibility is to implement a DownloadFileCompleted. In the event, look at the Error, it will give you precious clues about why it failed.
Found a solution:
if (!Directory.Exists(directores[directores.Length - 2]))
Directory.CreateDirectory(directores[directores.Length - 2]);
string path = Path.GetDirectoryName(Application.ExecutablePath) +
"\\" + directores[directores.Length - 2] +
"\\" + Path.GetFileName(url_img).Replace(" ", "_");
if (!Directory.Exists(directores[directores.Length - 2])) Directory.CreateDirectory(directores[directores.Length - 2]);
client.DownloadFileAsync(new Uri(url_img), path);
Thanks for trying help.
So this function doesn't create folder if it doesn't exist, we have to create it before.
Related
Actually I'm trying to create zip file of a directory and but the ZipFile.CreateFromDirectory() giving below Exception.
System.IO.IOException : The process cannot access the file
PATH_TO_CREATE_ZIP/file.zip' because it is being used by another
process.
Following is the Code Snippet for it. :
public void createZipFile(string zipPath, string archiveFileName)
{
string DirectoryToBeArchive = zipPath + "\\" + archiveFileName;
if (Directory.Exists(DirectoryToBeArchive + ".zip"))
{
File.Delete(DirectoryToBeArchive);
ZipFile.CreateFromDirectory(zipPath, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
}
else
ZipFile.CreateFromDirectory(zipPath, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
Directory.Delete(DirectoryToBeArchive);
}
Help Would be Much Appreciated. Thanks in Advance. :)
It only makes sense you get this exception. Let's investigate your code step by step:
createZipFile("C:\\Temp", "myZipFile");
public void createZipFile(string zipPath, string archiveFileName)
{
//DirectoryToBeArchive = "C:\\Temp\\myZipFile"
string DirectoryToBeArchive = zipPath + "\\" + archiveFileName;
//Some logical error here, you probably meant to use File.Exists()
//Basically, as you can't find a directory with name C:\\Temp\\myZipFile.zip, you always jump into else
if (Directory.Exists(DirectoryToBeArchive + ".zip"))
{
File.Delete(DirectoryToBeArchive);
ZipFile.CreateFromDirectory(zipPath, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
}
else
//It will try to overwrite your existing "DirectoryToBeArchive".zip file
ZipFile.CreateFromDirectory(zipPath, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
//This won't work as well btw, as there probably is no directory
//with name C:\\Temp\\myZipFile
Directory.Delete(DirectoryToBeArchive);
}
Though, even if you delete the file, you will probably hit same error.
The thing is when you try zipping the folder C:\\Temp into the file C:\\Temp\\myZipFile.zip you will also try zipping the file itself. That's actually where you get the file is being used error.
So,
Replace Directory.Exists() with File.Exists()
Zip in another folder
Just a friendly warning, I'd be cautious with Directory.Delete() if I were you :)
My issue was, the output folder and zipping folder was the same.
Moved to separate folders, now working fine.
Correct Code :
this piece of code after little correction worked for me..
string DirectoryToBeArchive = zipPath + "\\" + archiveFileName;
if (File.Exists(DirectoryToBeArchive + ".zip"))
{
File.Delete(DirectoryToBeArchive + ".zip");
ZipFile.CreateFromDirectory(DirectoryToBeArchive, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
}
else
ZipFile.CreateFromDirectory(DirectoryToBeArchive, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
Directory.Delete(DirectoryToBeArchive , true);
Can anyone help with this? I keep getting an error File beeing used by another process.
Here's my code so far:
string username = textBox1.Text;
string password = textBox2.Text;
string SecurityCode = textBox3.Text;
if(!Directory.Exists(path + "\\Login"))
Directory.CreateDirectory(path + "\\Login");
if (!File.Exists(path + "\\Login\\Username.omg" + "\\Login\\Password.omg" + "\\Login\\SecurityCode.omg"))
File.Create(path + "\\Login\\Username.omg");
File.Create(path + "\\Login\\Password.omg");
File.Create(path + "\\Login\\SecurityCode.omg");
File.AppendAllText(path + "\\Login\\Username.omg", username);
File.AppendAllText(path + "\\Login\\Password.omg", password);
File.AppendAllText(path + "\\Login\\SecurityCode.omg", SecurityCode);
MessageBox.Show("User Created: Welcome: " + username);
}
File.Create returns a Stream that you need to close before trying to access the file just created
using(File.Create(path + "\\Login\\Username.omg"))
;
using(File.Create(path + "\\Login\\Password.omg"))
;
using(File.Create(path + "\\Login\\SecurityCode.omg"))
;
a simple using statement around the File.Create call could help to close and dispose the returned stream
However, as stated in the comments above from Mr Hans Passant, your simple scenario could be served better by a simple call to File.WriteAllText()
File.WriteAllText(Path.Combine(path, #"login\username.omg"), username);
File.WriteAllText creates the file if it doesn't exist and overwrite its content if it exists. In your code, instead, you append the info to the same files over and over.
I am not sure that this is really what you want here.
By the way, your call to File.Exists is wrong. You should test each file separately
string userNameFile = Path.Combine(path, #"login\username.omg");
if (!File.Exists(userNameFile)
{
using(File.Create(userNameFile))
;
}
I am trying to download a file stored in a folder.
string path = "D:\\app_data\\Clients\\Client " + jobdescription.ClientID + "\\Job " + jobdescription.JobDescriptionID + "\\";
string file = Path.Combine(path, jobdescription.JobTitle + ".docx");
return File(path, "application/docx", jobdescription.JobTitle + ".docx");
The error generated is:
Server Error in '/' Application.
Could not find a part of the path 'D:\app_data\Clients\Client 1\Job 2\'
But the file with specified filename is in the folder. What am i doing wrong ?
You use path instead of using file, in your third line.
It should read:
return File(file, "application/docx", jobdescription.JobTitle + ".docx");
The odd thing is that something like System.IO.File.Delete() works
and the file gets deleted but will give "access to path is denied error" for .Move() operation.
All files are located in the same folder, user "Network service" has all
full control rights for the folder and all subfolders in it etc.
Folders are located in the project directory and can be seen in solution explorer.
Exception Details: System.UnauthorizedAccessException: Access to the path is denied.
foreach(var info in FileActions.Where(x => x.OldSortOrder != x.SortOrder))
{
string FileToRename;
string NewName;
string OldFilePath;
string OldFileThumbPath;
FileToRename = info.ProductID + "/" + info.OldSortOrder + "-" + info.ImageID + ".jpg";
NewName = info.SortOrder + "-" + info.ImageID + ".jpg";
OldFilePath = System.Web.HttpContext.Current.Request.MapPath("~/Content/ProductImages/" + FileToRename);
OldFileThumbPath = System.Web.HttpContext.Current.Request.MapPath("~/Content/ProductImages/" + info.ProductID + "/thumbs/" + FileToRename);
System.IO.File.Move(OldFilePath, NewName);
System.IO.File.Move(OldFileThumbPath, NewName);
}
Its because you map the path for the first files but not for the NewName.
So did not have the full path to know what to rename/move the file, and needs the full path to work correctly.
With out the path this is probably try to move it on the default folder of the asp.net pool that is probably don't have this permissions.
So the code will be
NewName = System.Web.HttpContext.Current.Request.MapPath("~/Content/ProductImages/"
+ info.SortOrder + "-" + info.ImageID + ".jpg" );
and debug this lines to see if the directories and files are all correct.
I have encountered a strange problem when using the File.Move command. The Programm actually moves and renames the file, but then throws me an exception that the sourcefile is not found; - what is expected because the File was moved.
The Program works fine if i catch the Exception but i'm wondering why i get these exception.
My Code:
foreach (string str in CPM.prot.FKFinishedBad)
{
try
{
string dir = System.Configuration.ConfigurationSettings.AppSettings["ResultDir"] + "\\" + DateTime.Now.ToString("yyyy_MM_dd") + "_Bearbeitete Protokolle";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.Move(System.Configuration.ConfigurationSettings.AppSettings["ResultDir"] + "\\" + str + "_" + CPM.LastJob + ".txt", dir + "\\" + "\\" + str + "_" + CPM.LastJob + "_Nachproduziert" + ".txt");
}
catch (Exception e)
{
}
}
Make sure that each item in CPM.prot.FKFinishedBad is unique - that may be a cause of the phenomenon.
Also, I'd recommend to refactor the code: the directory lines don't need to be repeated and should be outside of the loop.
And please learn to use String.Format and Path.Combine.
Are you sure all of your files exist?
It might happen that one of them is missing (which explains the exception), while the others are processed correctly. you can also check them before the move with File.Exists.
Also, be careful when using empty catch blocks, they can cause a lot of headaches when debugging.
Try to suspend a thread for a half a second (or less) here:
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
//suspend thread for 0.5 sec
}
This is probably related to fact that you create a directory and immediately move a file. So suspend a thread to let "breath" to system.
I have just been experiencing this problem, it took me a while to realise that there is a FileInfo.MoveTo command which appears to do the same thing.
However it doesn't throw an exception, and works.
It is a bit dodgy if there are two ways to do one thing and only one of them works.