I am using WebClient.DownloadFile to download an image to a local repository as follows:
WebClient myWC = new WebClient();
myWC.Credentials = new System.Net.NetworkCredential(username, password);
string photoPath = #"\images\Employees\" + employee + ".jpg";
myWC.DownloadFile(userResult[12].Values[0].Value.ToString(), photoPath);
My expected results were as follows: My web app is deployed here:
C:\Inetpub\wwwroot\MyWebApp
I expected this to save the photo to
C:\Inetpub\wwwroot\MyWebApp\images\Employees...
Instead, all my photos get saved here:
C:\images\Employees
I guess I don't completely understand the DownloadFile method because I felt like the path should be relative to the directory the app is deployed in. How can I change the path so that it is relative to the directory of the app?
Note: I don't want to use a physical path because I have a Dev and QA site and I don't want the paths to break if things get moved around.
In an ASP.NET application you could use the Server.MapPath method to map to a physical folder within your web site relative to the root of your site (which is represented by ~):
string photoPath = Server.MapPath("~/images/Employees/" + employee + ".jpg");
The leading backslash in your photoPath makes the path an absolute path starting at the root directory (C:\ in your example). Do make it a relative path just remove the leading backslash:
string photoPath = #"images\Employees\" + employee + ".jpg";
Remark: DownloadFile(...) will not create the directory for you. Make sure it's there:
Directory.CreateDirectory("images\Employees");
string photoPath = #"images\Employees\" + employee + ".jpg";
doesn't work in powershell and gives the following error:
At line:1 char:22
+ string photoPath = #"images\Employees\" + employee + ".jpg";
+ ~
No characters are allowed after a here-string header but before the end of the line.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedCharactersAfterHereStringHeader
Related
I am trying to create a new directory using Directory.CreateDirectory(), but I am unable to understand why it does not create a new directory when I use the following code.
var directory = Path.Combine(Environment.CurrentDirectory, "Status" + "-" + "Test" + Guid.NewGuid() + "\\");
Directory.CreateDirectory(directory);
But when I manually feed the file path it creates the directory (works well).
Directory.CreateDirectory(#"F:\Code\Help\");
Am I doing it wrong?
Any comments or feedback is greatly appreciated. TIA.
There is nothing wrong with your code per-se
My suspicion is you are creating a directory (somewhere)
try
{
var directory = Path.Combine(Environment.CurrentDirectory, $#"Status-Test{Guid.NewGuid()}");
Console.WriteLine(directory);
var di = Directory.CreateDirectory(directory);
Console.WriteLine($"The directory was created successfully at {Directory.GetCreationTime(directory)}.");
Console.WriteLine($"==> { di.FullName}");
}
catch (Exception e)
{
Console.WriteLine("Oh NOES!: {0}", e);
}
Environment.CurrentDirectory Property
By definition, if this process starts in the root directory of a local
or network drive, the value of this property is the drive name
followed by a trailing slash (for example, "C:\"). If this process
starts in a subdirectory, the value of this property is the drive and
subdirectory path, without a trailing slash (for example,
"C:\mySubDirectory").
I'm trying to take input and convert that to a .csv file then create a directory for the folder and save that file within the directory. Once I run my code, I'm able to create the directory and file. However, this is supposed to happen after I click the button and does so before. The exception is thrown right after I click the button. I'm using WPF and coding in C#. What would cause this exception?
Here is a snippet
private void updateBANKEevent(object sender, RoutedEventArgs e)
{
//Convert input to CSV format
string userInput = tellerID.Text + "," + vaultSerial.Text + "," + QR.Text;
var bnkDir = #"C:\Program Files\Bank_Data";
//generate headers for CSV file
if (!Directory.Exists(bnkDir))
{
string bnkHeader = "tellerID" + "," + "Vault Serial Number" + "," + "QR Code" + Environment.NewLine;
Directory.CreateDirectory(bnkDir); <--Exception is thrown here
File.WriteAllText(System.IO.Path.Combine(bnkDir,"Bank_Data.csv"), bnkHeader + userInput);
}
// Append new input to existing file
File.AppendAllText(System.IO.Path.Combine(bnkDir),userInput + Environment.NewLine);
}
The exception is quite clear. The user is not authorised to create the specified directory.
Given that the folder is "C:\Program Files\Bank_Data" it will be the case that a regular user won't have the rights to create files or directories whereas an admin user (which you probably are) will.
You need to choose a folder that all users have rights to to store your data, which by default will be %APPDATA%\<your app>.
I would like to first create a new dir and then save a file into the following location C:\Users\Paul\Documents + \newfolder\nameOffile.xml.
Can this be achieved in C#. I currently have the following code but i cant seem to get it to work
XDocument doc = new XDocument(rootNode);
var dateAndTime = DateTime.Now;
var date = dateAndTime.Date.ToString("dd-MM-yyyy");
var patWithoutExtension = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
string savedFilePah = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
var savedFile = savedFilePah + "/" + Directory.CreateDirectory("newFolder") + "/" + patWithoutExtension + "_" + date + ".xml";
//var savedFile = "C:/tmp/" + patWithoutExtension + "_" + date + ".xml";
doc.Save(savedFile);
lblFileUploaded.Text = "Success!";
it keeps failing on the doc.save with the following error
An unhandled exception of type 'System.IO.DirectoryNotFoundException'
occurred in System.Xml.dll
Additional information: Could not find a part of the path
'C:\Users\Paul\Documents\newFolder\test2_29-03-2015.xml'.
The problem seems to be with Directory.CreateDirectory("newFolder") which will create the folder under the working directory rather than under C:\Users\Paul\Documents.
Also, as a good practice I would advice to store the newly created folder in a dedicated folder. The advantages of this are twofold - you'll be able to watch this variable easily during debugging thus find out the exact location of the created folder and also, if an exception will be thrown you'll know the exact location of it.
Also, some Windows APIs might not accept a forward slash ('/') but will except a backslash ('\').
You must specify the full path to the directory you want to create, otherwise it's created at the working (running) folder:
string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var myDir = Path.Combine(myDocs, "newFolder");
Directory.CreateDirectory(myDir);
var savedFile = Path.Combine(myDir, patWithoutExtension + "_" + date + ".xml");
This Directory.CreateDirectory("newFolder") is not creating the directory inside your Users folder: you're just passing it "newFolder", so it doesn't know that's where you want the folder. It will be creating it in your current working folder (e.g. bin/Debug).
Try passing the entire path to CreateDirectory:
string savedFilePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"newFolder");
Directory.CreateDirectory(savedFilePath);
I'm trying to store an image into two applications (both published on server). This is my code to save the image :
string path = Server.MapPath("/Images/Landing/bottom_banner/");
string path1 = #"_http://10.241.193.22/Myapplication/Images/Landing/bottom_banner/";
HttpPostedFileBase photo = Request.Files["adup"];
if (photo.ContentLength != 0)
{
string lastPart = photo.FileName.Split('\\').Last();
Random random = new Random();
int rno = random.Next(0, 1000);
photo.SaveAs(path + rno + lastPart);
photo.SaveAs(path1 + rno + lastPart);
}
Note: Myapplication is another application hosted on the same server
My problem is I am able to save the image in my first application using Server.MapPath but when the compiler comes to the part photo.SaveAs(path1 + rno + lastPart) it gives an error:
The SaveAs method is configured to require a rooted path, and the path '_http://10.241.193.22/Myapplication/Images/Landing/bottom_banner/676Chrysanthemum.jpg' is not rooted
Please suggest how can I eliminate this issue?
I am not sure whether this is right but can you do this ?
In the current application store the Server.MapPath value and then replace the current application name with "Myapplication" and then add the trailing path. Something like this
string path1 = Server.MapPath("");
path1.Replace("Application1", "Myapplication"); //Considering "Application1" is the name of your current application
path1 += "/Images/Landing/bottom_banner/";
HttpPostedFileBase photo = Request.Files["adup"];
if (photo.ContentLength != 0)
{
string lastPart = photo.FileName.Split('\\').Last();
Random random = new Random();
int rno = random.Next(0, 1000);
photo.SaveAs(path1 + rno + lastPart);
}
There might be a permission problem with this one. I have not checked it. If it works please let me know.
You should POST image to the second server and use same method (Server.MapPath) there.
It's impossible to save image (or other file) at remote server.
if you know absolute paths (for example) 'C:\Web\ApplicationOne...\image.png\' and 'C:\Web\ApplicationTwo...\image.png' you can replace path difference like this:
photo.SaveAs(path + rno + lastPart);
photo.SaveAs(path.Replace("ApplicationOne", "ApplicationTwo") + rno + lastPart);
Is it possilbe to create temp files and images in asp.net applications using something like this:
If no, how can i do it?
(ImagePB is a previously treated Bitmap)
if (System.IO.File.Exists(System.IO.Path.GetTempPath() + #"img" + imgID.ToString() + "PB" + extencao) == true)
{
try
{
System.IO.File.Delete(System.IO.Path.GetTempPath() + #"img" + imgID.ToString() + "PB" + extencao);
imagePB.Save(System.IO.Path.GetTempPath() + #"img" + imgID.ToString() + "PB" + extencao, imgFormat);
}
catch (Exception)
{ }
}
Yes, GetTempPath() should return a temporary file path, and the code you have posted should work. http://msdn.microsoft.com/en-us/library/system.io.path.gettemppath.aspx has more information about how GetTempPath() get's the path.
Though, it does not verify if the Temp Path directory exists, or is writeable by the application. I haven't run into a situation where GetTempPath() does return an inaccessible path. You'd probably want to account for this in your application to handle this situation.
Also be mindful, this is very possibly C:\Windows\Temp. It could have limited disk space, or deleted at any time by someone else when disk space is needed. You may want to create a temp path within your application, and delete it when you no longer need it.