Programmatically Access a File on ASP.NET MVC4 - c#

As part of an ASP.NET MVC4 project I need to be able to read from and write to some XML files. I have trouble finding / accessing the files I need.
I've created a demo project to which I've added a folder /Documents containing some XML files.
So in the same project I have a folder /Classes with my class that should read the XML files using XDocument.load().
Here is what I'd like to do (and how I thought it should work):
string path = "/Documents/test.xml"; // Doesn't work
XDocument xml = XDocument.load(path);
However, this doesn't work. Not with "/Documents", "Documents" or "~/Documents".
Supplying the full path works, but not very useful if the website is going to be deployed in other environments.
string path = "D:/Projects/Demo/Demo/Documents/test.xml"; // Works
XDocument xml = XDocument.load(path);
Any suggestions how I can access the files using some kind of relative path?

use Server.MapPath to get the absolute path.
string path = Server.MapPath("/Documents/test.xml");
XDocument xml = XDocument.load(path);

Use HttpContext.Current.Server.MapPath
string path = HttpContext.Current.Server.MapPath("/Documents/test.xml");

Have you tried:
var path = Server.MapPath("/Documents/test.xml");

Related

Xamarin Android project can't find XML file

I have a file in my Xamarin Android project called "SaveData.xml". I can't save it in the assets folder because I need to write to it during runtime. I am trying to access it with my LoadXML() function:
XmlDocument doc = new XmlDocument();
XmlDocument saveData = new XmlDocument();
public void LoadXML()
{
saveData.Load("SaveData.xml");
//This bit works fine.
AssetManager assets = this.Assets;
using (StreamReader sr = new
StreamReader(assets.Open("Spices.xml")))
{
doc.Load(sr);
}
}
I've tried reading up on it but all the answers say to just save in assets folder. I can't do that because I need to write to this file and then read it again every time the app starts. I also tried putting it in the resources folder and changing the build action. Is the file path wrong? do I need to save it somewhere else? I'm stumped.
EDIT: Sorry for not being specific. "saveData.Load("SaveData.xml")" Is throwing a file not found exception and I want to know why.
Here is the xml file.
SaveData.xml
<?xml version="1.0" encoding="utf-8" ?>
<list>
<cupboard></cupboard>
<shoppingList></shoppingList>
</list>
Yes, if you need to write to the xml during runtime application, we can't put it into the assets folder as it's read-only.
Besides, when you execute saveData.Load("SaveData.xml"), you're not specifying a target directory, so it's defaulting to the root directory, then it will throw a file not found exception.
So you'll need to write the file to a location you have write access to.
The code below will specify a file in the user's home directory, which will be writeable:
using System.IO;
string backingFile_path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "SaveData.xml");
For more details, you can check: https://learn.microsoft.com/en-us/xamarin/android/platform/files/
Note:There is a sample included in this link which you can refer to.

how to read a file from a different project?

how to read a file from a different project?
I have a solution:
Solution1
-MyProject
-MyProject.Artifacts
----Message.XML
-MyProject.Tests
I am attempting to read the contents of Message.XML from MyProject.Tests.
How do I read the contents of Message.XML from MyProject.Tests?
Unfortunately, right now I'm doing something like this, but it's not very pretty:
var currentDir = Directory.GetCurrentDirectory();
var parentDir = Directory.GetParent(Directory.GetParent(currentDir).FullName).FullName;
var parentParentDir = Directory.GetParent(Directory.GetParent(Directory.GetParent(currentDir).FullName).FullName).FullName;
var parentParentParentDir = Directory.GetParent(Directory.GetParent(Directory.GetParent(Directory.GetParent(currentDir).FullName).FullName).FullName).FullName;
You can store a path to the file in app settings of app.config / web.config using that read the file contents.
That way if you need to deploy your software in a different way you have the flexibility
If your path is fixed, you can write the path like "c:\projects\solution ... Message.xml"
If you want a relative path, the simplest way is this:
var DI = new DirectoryInfo("..\\..\\..\\..\\Your Folder\\Message.XML");
This path is started from CurrentDirectory and goes four folders up and the one folder down and finds the file.

c# clickOnce xml file not found

C# deployment clicOnce. Setup run xml file not found?
XDocument x = XDocument.Load(#"veri.xml");
image1:
http://www.kgmmp.org/333.jpg
If it is a file in the project, check whether it is copy local from the file's properties. file must be copy local. then you can try the following.
XDocument x = XDocument.Load(#"veri.xml");
string filePath = Path.Combine(
HostingEnvironment.ApplicationPhysicalPath,
#"App_Data\AppSettings.xml"
);

How do i get a relative path of a file when running my code in debug for coded ui

I'm trying not to hard code my path, but I have not been able to figure our a way to get to an xml file that I have included in my project under a folder labeled Datasource. Here is my latest code that I have tried which still doesn't work.
public static string myAssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
string fileName = xmlFileName;
string path = Path.Combine(myAssemblyDirectory, #"DataSource\" + fileName);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(path);
Here is the output for the path that I'm getting which is putting it in my test results output folder.
"C:\MyAutomation\Automated_Test_Projects\AutomationProjects\MiserReleaseTestSuites\TestResults\marcw_ISD2005M 2016-02-05 10_15_17\Out\DataSource\Miser_Login_Dts.xml"
If possible I'd like to point it to
"C:\MyAutomation\Automated_Test_Projects\AutomationProjects\MiserReleaseTestSuites\MiserReleaseTestSuites\DataSource\Miser_Login_DTs.xml"
".." Can be used to go to the relative parent directory. "." Refers to the current directory.
You can combine these to form a relative path that starts higher up in the directory tree.
In your example you need to go 3 directories higher than the out folder and then into the MiserReleaseTestSuites\DataSource folder. Combining this produces
#"..\..\..\MiserReleaseTestSuites\DataSource\"
You can deploy the file in the same manner as you would when data driving the tests. See https://stackoverflow.com/a/25742114/546871
The TestContext class contains several fields with "directory" in their names. These can be used to access the various directories associated with running the tests. See also https://stackoverflow.com/a/19682311/546871

Loading an XML file path in C#

I'm trying to load an XML-file, located in a folder in my project (using Visual Studio 2012).
The structure is this:
solutionRoot\
- service\
-- ServiceClass.cs
-- AppValues.xml <-- this is the file I want to load
In my ServiceClass, I'm trying to read from the XML-file with the following code:
public String GetXmlElement(String elementName)
{
[....]
XDocument document = XDocument.Load(#"\service\AppValues.xml");
[...]
}
Which gives the following error, when I'm trying to test the code:
Test method PandaTests.ServiceTest.ReadXmlCanReadXml threw exception:
System.IO.DirectoryNotFoundException: Could not find a part of the path
'C:\Users\MyName\Documents\GitHub\project\Project22\PandaTests\bin\Debug\service\AppValues.xml'.
It's obviously a problem with my path, but I can't figure out how to get the relative path right. I've looked at other questions here on stack overflow, but many of them seem overly involved. Is there an easy way to load the XML-file without giving an absolute path?
When VS runs your program, your working directory is set to the Debug/Release folder, not to your solution root.
You have a couple options that I know of...
Use an absolute path, but you don't want this
Set your file to copy into your working directory on build. You do this by modifying the properties of the file in the solution explorer. Thanks to T.Roland in the comments below: Set Copy to Output Directory to Copy if Newer and set Build Action to Embedded Resource;
Modify your solution's working directory to be your solution root This thread offers different ways to accomplish that.
I faced the same problem and solved it using "Server.MapPath"
For example,
string path=Server.MapPath("~/service/AppValues.xml");
XDocument document = XDocument.Load(path);
Hope it helps.
Bring up the properties in Visual Studio for AppValues.xml. Change "Copy to Output Directory" to "Copy if Newer", and build the project.
check this
XDocument document = XDocument.Load(#"..\service\AppValues.xml");
Set the build action of the xml file to be "Embedded resource" and then reference using this code
private static UnmanagedMemoryStream GetResourceStream(string resName)
{
var assembly = Assembly.GetExecutingAssembly();
var strResources = assembly.GetName().Name + ".g.resources";
var rStream = assembly.GetManifestResourceStream(strResources);
var resourceReader = new ResourceReader(rStream);
var items = resourceReader.OfType<DictionaryEntry>();
var stream = items.First(x => (x.Key as string) == resName.ToLower()).Value;
return (UnmanagedMemoryStream)stream;
}
var file = GetResourceStream("appValues.xml");
When adding a file to Visual Studio project, by default it is not copied to the generated output. As such, you need to set to either copy the file or do so manually.
To set the file to automatically copy, select it in solution explorer, right click and select properties. Update the value for "Copy to Output Directory" to "Copy Always". This will ensure a copy of the file is available at runtime in a subfolder of the resultant solution.
You can then load the file using something like:
string path = System.Io.Path.Combine(Application.StartupPath, #"\service\AppValues.xml");
XDocument doc = XDocument.Load(path);
I solved it in 2 steps. I'm using MVC and I had to use this in a class file.
1) String path
=HttpContext.Current.Server.MapPath("~/App_Data/yourxmlfilename.xml");
XDocument doc = XDocument.Load(path);
2) Change XML file properties
Build Action: Content
Copy to Output Directory: Copy always

Categories

Resources