load file from relative path - c#

I am currently doing this:
XDocument feedXml = XDocument.Load("C:/NewsFeed/NewsFeed/App_Data/WorldNews.xml");
But I'd like to use a relative path, so I I've tried the following:
XDocument feedXml = XDocument.Load("~/App_Data/WorldNews.xml");
And set the property, Copty to Output Directory, to "Copy Always".
But I'm getting the following error:
An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code
Additional information: A part of the path 'C:\Program Files (x86)\IIS Express\~\App_Data\WorldNews.xml' was not found.
Any help please?

XDocument.Load doesn't know anything about mapping paths. Instead, you should use HttpServerUtility.MapPath to map the path, then pass the result into XDocument.Load:
var path = HttpContext.Current.Server.MapPath("~/App_Data/WorldNews.xml");
var feedXml = XDocument.Load(path);

Related

What file does FromFile pull from?

This is my first time trying to use images in my code. I cannot figure out what file the FromFile command pulls from.
firstDice.Image = Image.FromFile(fDice.ToString() + ".png");
I am trying to get the image to correspond with whatever the random number fDice is.
Here is my error message:
System.IO.FileNotFoundException: '5.png'
Environment.CurrentDirectory
As Steve says in his comment, you must specify the full path otherwise.
You can use Path.Combine to create a path based on the current working directory. Such as:
Path.Combine(Environment.CurrentDirectory, "Images");

Error the relative path of resources folder auto change to absolute path in C#

The code below i use to read lines from file test.txt in my folder Resources of my project.
string[] test = File.ReadAllLines(#"Resources\test.txt");
The properties are already change to "Content" and "Copy Always".
When i run the program, somtimes the path auto change to the Absolute path as:
"C:\Users\Documents\Resources\test.txt
And the program error because cannot find the path.
You are using a relative path to the file, which relies on the CurrentDirectory being valid. This is either changing, or not being set to the desired directory when the program is executed. You can test this failure with this code:
string CurrentDirectory = Environment.CurrentDirectory;
Log.Trace($"CurrentDirectory = {CurrentDirectory}");
System.IO.File.ReadAllText(#"Resources\test.txt");
Environment.CurrentDirectory = #"C:\Tools";
// changing the current directory will now cause the next command to fail
System.IO.File.ReadAllText(#"Resources\test.txt");
You should not rely on the CurrentDirectory path being set correctly. Get the directory of the current running executable with something like this:
string ExePath = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location)
.Directory.FullName;
string FullPath = System.IO.Path.Combine(ExePath, "Resources", "test.txt");
System.IO.File.ReadAllText(FullPath);
Yo could use
Path.Combine(AppDomain.CurrentDomain.BaseDirectory , "Resources", "test.txt"
to get the path.
But to your problem: I think, the problem is the ReadAllLines, because it wants to convert the string to an absolute path. So the problem shouldn't exist anymore, if you localize the string, or even make somenthing like:
var path = "" + "Resources\\test.txt";
var test = File.ReadAllLines(path);
I couldn't test this though because I couldn't reproduce your problem.

c# Access to path denied?

I'm having trouble with an error. I have searched the web but havent found an answer that made sense to me. I'm basically trying to create a temporary text file, and write to it. Here it the code concerning the error:
using ( StreamWriter output = new StreamWriter(File.Create(GetTemporaryDirectory())))
and the getTemporaryDirectory method:
public string GetTemporaryDirectory() {
string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
string tempFile = Path.ChangeExtension(tempDirectory, ".txt");
Directory.CreateDirectory(tempFile);
return tempFile;
}
and last but not least the error:
dir = C:\Users\Jack Givens\AppData\Local\Temp\5ftxwy31.txt
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
Additional information: Access to the path 'C:\Users\Jack Givens\AppData\Local\Temp\0lpe1k5t.txt' is denied.
If anyone can tell me what is wrong with my code and what i need to do to fix it, I will appreciate it. side note: sorry for crappy code, i'm kinda a beginner :)
Directory.CreateDirectory(tempFile);
You have just created a directory, the name of which ends in "*.txt".
Then you attempt to create a file with the exact same path. But that's not possible.
You call CreateDirectory on your filename so now a folder exists in the path that File.Create is attempting to call. Just simply remove the Directory.CreateDirectory(tempFile); line (it is not needed as the folder is guaranteed to exist) and your code should work.
You are creating a directory, not a file. You can't open a directory as a file.

Error replacing xml file #C:\Windows\System32\WindowsPowerShell

I am writing a console application where I'm trying to replace a xml file (xx.config) with other xml file(xx.config) which is at different folder with different data to the path C:\Windows\System32\WindowsPowerShell.
I'm getting following error
Could not find a part of the path C:\Windows\System32\WindowsPowerShell\xx.config
But there is the file at this path. I tried to load this file to XMLDocument then also same error occurred. Can anyone tell me what I'm doing wrong.
XDocument xmldoc = XDocument.Load(#"C:\test\xx.config");\loads good
XDocument xmldoc = XDocument.Load(#"C:\Windows\System32\WindowsPowerShell\xx.config");\error occurs
File.Move(#"C:\test\xx.config", >#"C:\Windows\System32\WindowsPowerShell\xx.config");\error occurs

loading xml document error in c#

I'm trying to load a document with xml in c#
the name of xml file is variable, here is problem...
string filename="test01.xml";
XmlDocument root = new XmlDocument();
root.Load(filename);
the above code give me error: unable to connect to remote server or unable to load
but the following code works
XmlDocument root = new XmlDocument();
root.Load("test01.xml");
why is that?
You can try to specify the whole path (absolute path) to the file (not only the filename).
So instead of writing "test01.xml" you can try to write "C:\[... path to the file here]\test01.xml" and it should work as intended.
If you specify only the file name, the application will probably look for the file in the current directory (value in Environment.CurrentDirectory). I just tested this in a sample application.
It's worth mentioning that if you use FileName property from OpenFileDialog class as a case with 'using variable', it contains PATH to the file (despite its name ;)).
Does your XML contains DTD declaration with URL? Most probably parser tries to resolve it, and fails, because, say, automatic proxy does not accept its request.

Categories