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);
Related
So, I made a speech recognizer and it was working fine, I'm not sure why is it giving me this error right now. Any ideas?
String res = e.Result.Text;
string yol = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string settings = ("#" + yol + "\\" + "settings" + "\\");
if (res == "Hi Bot")
{
pictureBox1.Image = Image.FromFile(settings + "mybot.png"); -->That's where i get the error
say(greetings_random());
}
string yol = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string settings = ("#" + yol + "\\" + "settings" + "\\");
This means that settings has the value "#C:\Path\To\Executable\settings\".
That's probably not what you want -- I'm not sure what the # is trying to achieve, but it's not valid at the beginning of a path like that.
For future, debugging this code and inspecting the settings variable would quickly have shown the problem.
That said, it's recommended to use Path.Join (.NET Core 2.1+) or Path.Combine instead of string concatenation to create paths like this.
I have a DirectoryNotFoundException on a .txt file if I use the full path it's working but I don't want to use the full path because I want the program work no matter where it is placed (compatibilty with the maximum of computer)
Here's my code
private void SaveClose_Click(object sender, RoutedEventArgs e)
{
if (Windowed.IsChecked == true)
windowed = true;
else
windowed = false;
string textWriteWindowed;
if (windowed == true)
{
textWriteWindowed = "-screen-fullscreen 0" + Environment.NewLine;
}
else
{
textWriteWindowed = "-screen-fullscreen 1" + Environment.NewLine;
}
var selectedResolution = ResolutionBox.SelectedItem.ToString();
var split = selectedResolution.Split('x');
widthChoose = Int32.Parse(split[0]);
heightChoose = Int32.Parse(split[1]);
string textWriteWidth;
textWriteWidth = "-screen-width " + widthChoose + Environment.NewLine;
string textWriteHeight;
textWriteHeight = "-screen-height " + heightChoose + Environment.NewLine;
File.WriteAllText(#"\Resources\arguments.txt", textWriteWindowed);
File.AppendAllText(#"\Resources\arguments.txt", textWriteWidth);
File.AppendAllText(#"\Resources\arguments.txt", textWriteHeight);
this.Close();
}
The first argument of File.WriteAllText takes a path as input. Whatever you have mentioned is not the absolute path but it is just the relative path of the file. WriteAllText creates the file but doesn't create the directory by itself. So something like:
File.WriteAllText(#"\arguments.txt", textWriteWindowed);
shall work (and create the file in the respective drive), but
File.WriteAllText(#"\Resources\arguments.txt", textWriteWindowed);
shall not work. Hence, if you want to create a file in the path where the application resides, you can do something like:
string folder=Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
File.WriteAllText(#"\arguments2.txt", "ABC");
If you want to create a directory, then you could do something like:
System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create();// If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, textWriteWindowed);
Hope this answers your query.
you have to check whether the folder is exist before save the file,
if folder not exist create it using
Directory.CreateDirectory(...)
Directory.Exists(..)
you can use to check folder existence
IF you wanted to get the local path of the file you are executing use this:
var fInfo = new FileInfo(System.Reflection.Assembly.GetCallingAssembly().Location);
From there, you would do the following:
var parentDir = new DirectoryInfo(fInfo.DirectoryName);
var subDir = new DirectoryInfo(parentDir.FullName + "Resource");
if(!subDir.Exists)
subDir.Create();
This would ensure that you always have a folder in the directory of your executable. But just so you know, this is absolutely horrible code and should never ever be implemented in a production like environment. What if some knucklehead sysAdmin decides to place your program/folder in an area that the current user does not have access/writes too? The best place to write to is %APPDATA%, this will ensure the user always has read/write permissions to what you are trying to accomplish.
I don't know how but doing that worked for me :
File.WriteAllText(#"./arguments.txt", textWriteWindowed);
File.AppendAllText(#"./arguments.txt", textWriteWidth);
File.AppendAllText(#"./arguments.txt", textWriteHeight);
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'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);
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