Reading/Accessing to app settings value issue - c#

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();

Related

Reading a setting file on server

I am writing a web service which currently needs to read some settings from a json file on server.
string allSettingsTxt = File.ReadAllText(settingsPath);
List<MySetting> list = JsonConvert.DeserializeObject<List<MySetting>(allSettingsTxt);
I tried giving following for the path
string settingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"..\MyCurrentDir\setting.json");
But this path wont resolve on the actual deployment, I believe it has to be something like http://servername/settings/setting.json ??
Where can I store such json file
what path I should use to access it?
I'm not totally sure if I understand correctly what you are trying to achieve.
I assume you want to get the path of the settings file which is relative to your executable file.
This is what I do often in my own code:
var configFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "config.xml");
In this case, config.xml is expected to be in the same directory as the .EXE.
So this would be
var settingPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"..\MyCurrentDir\setting.json");
in your case.
Also see https://dailydotnettips.com/different-ways-of-getting-path/ for some explanations.

System.UnauthorizedAccessException has been thrown: Reading from JSON file

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

How to give path to an text file in Solution using XDocument?

I want to load a xml document Swedish.xml which exists in my solution. How can i give path for that file in Xamarin.android
I am using following code:
var text = File.ReadAllText("Languages/Swedish.txt");
Console.WriteLine("text: "+text);
But i am getting Exception message:
Could not find a part of the path "//Languages/swedish.txt".
I even tried following lines:
var text = File.ReadAllText("./Languages/Swedish.txt");
var text = File.ReadAllText("./MyProject/Languages/Swedish.txt");
var text = File.ReadAllText("MyProject/Languages/Swedish.txt");
But none of them worked. Same exception message is appearing. Build Action is also set as Content. Whats wrong with the path? Thanks in advance.
Just try with this
string startupPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName, "Languages", "Swedish.txt");
var text = File.ReadAllText(startupPath);
Try...
Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments)+"/Languages/Swedish.txt"
If you mark a file as Content Type, it will be included in the app bundle with the path that you are using within your project file. You can inspect the IPA file (it's just a renamed zip) that is created to verify that this is happening.
var text = File.ReadAllText("Languages/Swedish.txt");
should work. The file path is relative to the root of your application. You need to be sure that you are using the exact same casing in your code that the actual file uses. In the simulator the casing will not matter, but on the device the file system is case sensitive, and mismatched casing will break the app.
I've looked into this before and never found any solution to access files in this way. All roads seem to indicate building them as "content" is a dead end. You can however place them in your "Assets" folder and use them this way. To do so switch the "Content" to "AndroidAsset".
After you have done this you can now access the file within your app by calling it via
var filename = "Sweedish.txt";
string data;
using
(var sr = new StreamReader(Context.Assets.Open(code)))
data = sr.ReadToEnd();
....

string file path is not working c#

Okay I have spent an inordinate amount of time trying to solve what the posts i've read say is a simple fix.
I want to write to a file in my documents and here is my code.
string st = #"C:\Users\<NAME>\Documents\Sample1.txt";
System.IO.StreamWriter file = new System.IO.StreamWriter(st);
file.WriteLine(Convert.ToString(Sample1[0]));
file.Close();
Where is the user name. I am getting the following error
"A first chance exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.ni.dll. An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.ni.dll but was not handled in user code"
I am using Visual Studio Express for Windows Phone Development.
If anyone can point out what i am doing wrong i would be grateful.
Thanks.
I assuming you're using the string as you've posted it. If thats the case you should use the SpecialFolder Enum instead.
var st = string.format(#"{0}\Sample1.txt",
Environment.GetFolderPath(Environment.SpecialFolder.Personal));
You should take advantage of the Environment.SpecialFolder enumeration and use Path.Combine(...) to create a path:
var path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Personal),
"Sample1.txt");
using (var sw = new StreamWriter(path))
{
sw.WriteLine(Convert.ToString(Sample1[0]));
}
Also, StreamWriter should be placed within a using statement since it is disposable.
To get MyDocuments use:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
This will return the path to MyDocuments on the host computer.
You can see a list of SpecialFolders on MSDN: http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx
EDIT: I just noticed you were developing for Windows Phone. Read up on the other SpecialFolders on MSDN.

How do I get GetResourceStream to read files that have an extension other than .txt?

I have the following code:
var resource = System.Windows.Application.GetResourceStream(new Uri("movies.txt", UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
string z = streamReader.ReadToEnd();
When I change the movies.txt extension to movies.plist, the code no longer functions, even though the file is still plain text. How do I solve this? I need to keep the file extension as .plist.
The error I get is NullReferenceException on the second line.
EDIT: I realized after posting this that this solution isn't available in Windows phone environments.
If all you want to do is read a text file it might make more sense to use:
string result = System.IO.File.ReadAllText("myTextFile.ext");
Is there any particular reason you want to use StreamReader specifically?
Try using the System.IO.FileInfo class to open a file. That will let you open a FileStream.
var file = new System.IO.FileInfo("c:\foo.bar");
var FileStream = file.OpenRead();
Byte b = (Byte)FileStream.ReadByte();
Debug.WriteLine(b.ToString());
Edit: Corrected code.

Categories