im trying to create an xml file and then save it to a file location...
string xmlPath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "cities.xml";
XDocument doc = new XDocument(
new XElement("Cities",
new XElement("City",
new XAttribute("id", gid),
new XElement("CityName", cityname))));
doc.Save(xmlPath);
the problem is that its not being saved to the location specified...
Try to use the System.IO.Path.Combine method to make sure you a) have the necessary backslash between the directory and the file name, and to b) make sure you don't have multiple of those:
string xmlPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"cities.xml");
Also: maybe your user account doesn't have the permissions to write to that directory. Try using something like Isolated Storage or some other directory you're 100% sure that the user is allowed to write to.
The code looks fine and when I tested it locally it worked. Make sure that xmlPath points to a directory where the current user has write permissions. As a side note it would be better to use Path.Combine.
if you are using a windows application path will be pointing to the bin directory i think it is saving in bin directory
The best thing you can do is run this program through the debugger and check what the location is that is give in xmlpath variable, and also check if a normal local user has write permissions to this directory. There could be any number of problems with the folder or the path that is given. Without any other information however it is hard to give a more descript answer.
Related
So I'm making a Tic Tac Toe application and have created a Text file linked to the program to hold the following information:
the name
the time took to win
the difficulty
I know the timer is redundant for a quick game like Tic Tac Toe but I'll use it in the future for other programs.
My question is how can I find the full path of the file while only knowing the name of the file?
I want to do this using the program so it can be transferred to any computer and still be able to access the file without the user having to input it.
The code I've tried is:
string file_name = Path.Combine(Environment.CurrentDirectory, "Tic Tac Toe\\HighScores.txt");
But this just looks in the Debug folder, where the file isn't located. The application is entirely a console application.
Try to dedicate the file in a fixed sub directory:
\TicTacToe.exe
\settings\settings.cfg
So the path is dependent of your executable file.
You'll fetch the directory by calling Directory.GetCurrentDirectory()
You can set a desired directory by setting Environment.CurrentDirectory
A common way to handle this case is the one described above.
Another would be to use user specifiy directories like the %appdata% path and create a dedicated directory there.
%appdata%\TicTacToe\settings.cfg
Everytime your application starts it should lookup the folder %appdata%\TicTacToe\
If it is present, your application has been executed with this user.
If not, just create a new one, so we know it's the first run.
You can get the %appdata% path by calling
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Example of what i would have done
private void setUp(){
string filename = "settings.cfg";
string dir = "TicTacToe";
string appdata =Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullpath = Path.Combine(Path.Combine(appdata,dir),filename);
//check if file exists, more accurate than just looking for the folder
if(File.Exists(fullpath )){
//read the file and process its content
}else{
Directory.CreateDirectory(Path.Combine(appdata,dir)); // will do nothing if directory exists, but then we have a bug: no file, but directory available
using (FileStream fs = File.Create(fullpath))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
}
}
Hope it helped.
Perhaps have a configuration file for your application and store the directory name in there.
An old example from MS, but should still be applicable...
How to store and retrieve custom information from an application configuration file by using Visual C#
I have a strange problem: my .NET 4.0 WPF application is saving data to the ApplicationData folder.
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\myProgram\\";
99.9% of the cases are working great, but on some computers it returns the wrong folder - instead of returning the user folder it returns another folder:
C:\Users\<user>\AppData\Roaming\myProgram\ --correct
C:\Users\s\AppData\Roaming\myProgram\ --wrong
The wrong folder has no write/read permission so my program doesn't work.
It seems the program is running under a different user, but if I check the Task Manager the user is the logged one.
The problem seems to be occurring with domain users with few permissions.
Do you also create a text file to write?
If so save a file such as:
String path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var filePath = Path.Combine(path, "filetowrite.log"); // Handles whether there is a `\` or not.
if (File.Exists(filePath))
{
......................
}
Note also before doing any file operations, one should check if directory exists.
Im saving images from a URL list but trying to duplicate the folder structure locally.
I parse the URL to give me the folder structure I want :
Example:
URL = www.site.com/images/folder1/folder2/image
My local base folder is mydocs/site/images
I split the url string up and am able to recursively create the proper folder structure using:
if (!Directory.Exists(finalLocalFolder))
{
DirectoryInfo di = Directory.CreateDirectory(finalLocalFolder);
}
Everything works great UNTIL I try and save the image to the folder using :
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteUrl, finalLocalFolder);
In which case, I am told that access to that folder is denied.
"System.UnauthorizedAccessException: Access to the path
'mydocs\images\test\test1\test\2\3m' is denied."
So I am guessing that I need to create a step in the CREATEDIRECTORY area where I immediately grant access to that folder.
Is there an easy way to do this?
I can close this if you would like - but just to put up what my problem was... here it is:
In here: webClient.DownloadFile(remoteUrl, finalLocalFolder);
finalLocalFolder was ending up something like: "C:\mydocs\images\test\test2" when IT SHOULD HAVE BEEN "C:\mydocs\images\test\test2\theimagefilename.jpg"
Stupid moment. Sorry.
I have created a .msi by using VS2008 setup project. My application frequently writes some value in a .txt file in the application directory (C:\Program Files\MyApp\MyFile.txt). After insalling it in Win7, it raises an exception "Access to the path .... is denied."
But whenever I run it as administrator, no such exception occurs. Here is my sscce
string FilePath=Application.StartupPath + #"\AppSettings\CurrentUserName.inf";
using (StreamWriter writer=new StreamWriter(FilePath,false))
{
writer.Write(txtLoginName.Text.Trim());
}
MainForm.ProcessLogIn();
this.DialogResult = DialogResult.OK;
I don't know how to solve this problem. Any suggestion?
Move your file out of Program Files directory. In Win7 is readonly for normal users.
You could move the file in the ProgramData directory.
Your installer should create a directory for your application there.
Then inside your code you could retrieve the correct full pathname using these lines of code
string dataPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
string appFile = Path.Combine(dataPath, "MyAppDir", "MyFile.txt");
usually (on Win7) this result in a path like this
c:\programdata\MyAppDir\MyFile.txt
but using the SpecialFolder enum you are guaranteed to use a folder available in readwrite to your application not depending on the current operating system.
The only way to solve this problem is to not write to that folder. You are not allowed to write to that folder by convention, unfortunately, older versions of Windows did not hold you to this.
Instead, you can use Environment.SpecialFolder to help you find where you need to go:
// your application data for just that User running the app
var perUserAppData = Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData);
// your application data for ALL users running the app
var allUsersAppData = Environment.GetFolderPath(
Environment.SpecialFolder.CommonApplicationData);
// better!
var path = Path.Combine(perUserAppData, #"MyApp\MyFile.txt");
Basically, Windows 7 is telling you that you're going to have to stop driving on the sidewalks and use the street as was intended.
As a short-term fix, you can use ICACLS to grant write access to the file. Note: NOT the whole directory.
As a longer term fix, you should NOT write to the program directory if you are running as unprivileged users, but instead somewhere like %LOCALAPPDATA% or %APPDATA%.
I've been saving a small XML data file to an external drive, no probs. But then I tried to use the ApplicationData folder and others, even C:\ but no luck. I'm getting an error like "Access to the path "C:\" denied".
Just to confirm, the file is created and read fine with the current code, to an external drive. I guess this is something to do with security & permissions but I haven't found anything too useful.
Thanks in advance if you can point me in the right direction on this one!
string fipData = #"F:\IL2\SIIYM\SIIYM Data.xml"; // external drive ok :-)
//string fipData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
//string fipData = #"C:\";
// if the XML data file doesn't exist, create it
bool dataFileExists = File.Exists(fipData);
if (dataFileExists)
{
// read the XML values
XDocument xData = XDocument.Load(fipData);
//...
}
else
{
// create & save the XML data file
XElement xLastPath = new XElement(el_lastPath, "");
XElement xLastCode = new XElement(el_lastCode, "");
XElement xRoot = new XElement(el_root);
xRoot.Add(xLastPath);
xRoot.Add(xLastCode);
XDocument newDataFile = new XDocument();
newDataFile.Add(xRoot);
try
{
newDataFile.Save(fipData);
}
catch (Exception ex)
{
MessageBox.Show("Data file unable to be created. System message:{0}".Put(Environment.NewLine + Environment.NewLine + ex.Message));
}
}
In the comments to another answer you say this is a desktop application, so lets treat each location separately.
Under Vista and beyond, an ordinary user does not have rights to create files in the root directory of the system drive (usually C:). You can see this for yourself by opening C:\ in explorer, right clicking and trying to create a file - you should get a UAC prompt. So if you want to write to C:\ then your application needs to run as an administrator, via a suitable manifest demanding elevation, or by starting a separate process when you want to write to that location.
Application Data, Environment.SpecialFolder.ApplicationData should however work. If you output the actual directory that returns what do you get?
I can only imagine that the application must be running in the context of a user which does not have access to the local drive, e.g. an ASP.NET website running under the anonymous IIS account or a service account which only has access to the relevant network locations.
Most likely the external drive is formated with FAT. FAT does not support rights management for users, so saving there is ok.
Besides that the IIS User has no rights to the other folders like Adam mentioned already