I am trying to read a JSON file stored on my PC and then deserialize it using Json.Net to store into an object.
However when I try to read from it, I keep getting an 'System.UnauthorizedAccessException has been thrown. Access to the path '/Users/person/JsonFolder' is denied'
I have read a lot of SO posts about this same issue and I have tried running as Administrator, make sure I have administrative rights to the path, trying different ways of reading from file, you name it. I have tried it on multiple PCs with the same issue.
Am I just reading from file wrong? I feel like I am going crazy.
Any recommendations are much appreciated :)
public void ReadFile(string fileName)
{
dateofFile = #GetDateOfFile(fileName);
string filePath = #"/Users/person/Jsonfolder";
JsonFile json1 = JsonConvert.DeserializeObject<JsonFile>(File.ReadAllText(filePath));
using (StreamReader file = File.OpenText(filePath))
{
JsonSerializer ser = new JsonSerializer();
JsonFile json2 = (JsonFile)ser.Deserialize(file, typeof(JsonFile));
}
}
I figured out what the issue was. I was referencing the FOLDER and not the file IN the folder. Thanks everyone for your help
Related
I am trying to read an xml file that is present in one of the projects in my VS solution. Here's my code.
string path = HttpContext.Current.Server.MapPath(#"~\Resources\XmlDocument.xml");
XDocument document = XDocument.Load(path);
This works fine if my xml file is in the web project. But in reality I have my xml file in a different project under the same solution.
I cannot use Server.MapPath as this searches web project. I searched for an answer but did not find any solution that worked for me.
How can I access this xml file? I am trying to access this from a helper method in the same project.
Try this:
string path = HostingEnvironment.ApplicationPhysicalPath + (some path);
public void LoadXML()
{
if (System.IO.File.Exists(path))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<int>));
lock (new object())
{
using (TextReader reader = new StreamReader(path))
{
return (List<int>)(serializer.Deserialize(reader));
}
}
}
}
this is working for me.
Once you get your current directory, why not just navigate up a number of parent directories and then locate your file?
DirectoryInfo info = new DirectoryInfo(Environment.CurrentDirectory);
DirectoryInfo parent = info.Parent.Parent;
string file = Path.Combine(parent.FullName, #"your\path");
Here I use Environment.CurrentDirectory to get where the program is at now, but you can stack as many Parent elements as you need. Then you can combine the path to get to your file in the other project.
EDIT:
Once your application is running all the environment variables and Server.MapPath will give you the location that it is executing from (i.e. the path you are getting now). In light of this it may be easier to create a folder and reference this via it's full path. (C:\Data\myfile.xml)
I'm making an application that loads and saves profile nodes to an external xml document in my output directory. It worked fine when I was opening it from my Assets folder but since that is read only (I think) I need to have it read and write from the output directory or another folder.
Like this:
XmlDocument users = new XmlDocument();
users.Load("users.xml");
However I get this error when this code runs:
"System.IO.FileNotFoundException: Could not find file "/users.xml"."
I've ticked the secondary storage permissions but i'm still a bit confused about just referencing a file in the output directory.
Would also appreciate the help for saving too as I assume the same error will occur:
users.DocumentElement.AppendChild(user);
users.Save("users.xml");
Thank you in advance.
In xamarin form you can try this code to load xml file from PCL project.
var assembly = typeof(TestClass).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream(“PrjectName.FileName”);
using (var reader = new System.IO.StreamReader(stream))
{
var serializer = new XmlSerializer(typeof(List<BuildOptions>)); var listData = (List<T>)serializer.Deserialize(reader);
}
I'm currently working on a project that has an external site posting xml data to a specified url on our site. My initial thoughts were to first of all save the xml data to a physical file on our server as a backup. I then insert the data into the cache and from then on, all requests for the data will be made to the cache instead of the physical file.
At the moment I have the following:
[HttpPost]
public void MyHandler()
{
// filePath = path to my xml file
// Delete the previous file
if (File.Exists(filePath))
File.Delete(filePath));
using (Stream output = File.OpenWrite(filePath))
using (Stream input = request.InputStream)
{
input.CopyTo(output);
}
// Deserialize and save the data to the cache
var xml = new XmlTextReader(filePath);
var serializer = new XmlSerializer(typeof(MyClass));
var myClass = (MyClass)serializer.Deserialize(xml);
HttpContext.Current.Cache.Insert(myKey,
myClass,
null,
myTimespan,
Cache.NoSlidingExpiration,
CacheItemPriority.Default, null);
}
The issue I have is that I'm always getting exceptions thrown because the file that I'm saving to 'is in use' when I try a second post to update the data.
A colleague suggested using a Mutex class just before I left work on the Friday so I wonder if that is the correct approach here?
Basically I'm just trying to sanity check that this is a good way of managing the data? I can see there's clearly an issue with how I'm writing the data to a file but aside from this, does my approach make sense?
Thanks
Hello I'm trying to access this setting:
with following code:
string path = ConfigurationManager.AppSettings["swPath"].ToString();
StreamReader sr = new StreamReader(File.Open(path,FileMode.Open));
But I get following exception:
Object reference not set to an instance of an object.
May I ask where do I make a mistake? Thank you so much for your time.
Update issue for Ehsan Ullah:
Properties.Settings.Default.swPath = cestasouboru.Text;
Properties.Settings.Default.Save();
I think this isn't that helpful for you but how can I provide more helpful information?
the way you are reading is for AppConfig. Whereas you are reading from the custom settings.
read it like this
string path = Properties.Settings.Default.swPath;
to save it
Properties.Settings.Default.swPath = "your path";
Properties.Settings.Default.Save();
What am I doing wrong in the following code?
public string ReadFromFile(string text)
{
string toReturn = "";
System.IO.FileStream stream = new System.IO.FileStream(text, System.IO.FileMode.Open);
System.IO.StreamReader reader = new System.IO.StreamReader(text);
toReturn = reader.ReadToEnd();
stream.Close();
return toReturn;
}
I put a text.txt file inside my bin\Debug folder and for some reason, each time when I enter this file name ("text.txt") I am getting an exception of System.IO.FileNotFoundException.
It is not safe to assume that the current working directory is identical to the directory in which your binary is residing. You can usually use code like the following to refer to the directory of your application:
string applicationDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
string filename = System.IO.Path.Combine(applicationDirectory, text);
This may or may not be a solution for your given problem. On a sidenote, text is not really a decent variable name for a filename.
If I want to open a file that is always in a folder relative to the application's startup path, I use:
Application.StartupPath
to simply get the startuppath, then I append the rest of the path (subfolders and or file name).
On a side note: in real life (i.e. in the end user's configuration) the location of a file you need to read is seldom relative to the applications startup path. Applications are usually installed in the Program Files folder, application data is stored elsewhere.
File.ReadAllText(path) does the same thing as your code. I would suggest using rooted path like "c:......\text.txt" instead of the relative path. The current directory is not necessarily set to your app's home directory.
You can use Process Monitor (successor to FileMon) to find out exactly what file your application tries to read.
My suggestions:
public string ReadFromFile(string fileName)
{
using(System.IO.FileStream stream = new System.IO.FileStream(fileName, System.IO.FileMode.Open))
using(System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
return = reader.ReadToEnd();
}
}
or even
string text = File.OpenText(fileName).ReadToEnd();
You can also check is file exists:
if(File.Exists(fileName))
{
// do something...
}
At last - maybe your text.txt file is open by other process and it can't be read at this moment.