UWP ApplicationData LocalSettings - c#

I am working on UWP, I want to store paths somewhere, and I found ApplicationData.LocalSettings can do it.
But I got an error when I stored the share folder path through it because of the \ and I don't know why. Is there any good solution to it?
Here is the code,just simple:
var path = #"\\192.168.1.1\test";
ApplicationData.Current.LocalSettings.Values.Keys.Contains<string>(path);
ApplicationData.Current.LocalSettings.Values[path] = xxx;
The contains function and add function also throw COMException

UWP ApplicationData LocalSettings
We could reproduce this problem, it looks "\" char is not support but not "", for this scenario, the better way is using "path" string as key to replace path value-key. And I will report this problem.
ApplicationData.Current.LocalSettings.Values["path"] = xxxx;
Or replace the header \\ with empty.
var path = #"192.168.1.1\test";

I tried your code. LocalSettings cannot use path as a key since it contains the \ symbol.
For example,
String path = #"&&192.168.1.1&test"; // I replaced every \ with &
ApplicationData.Current.LocalSettings.Values[path] = "your string";
will save your string correctly.

Related

Is there a method to manage relative paths in C#? [duplicate]

I have xml files that contain href file paths to images (e.g. "....\images\image.jpg"). The hrefs contain relative paths. Now, I need to extract the hrefs to the images and turn them into absolute paths in the file system.
I know about the GetFullPath method, but I tried it and it only seems to work from the CurrentDirectory set, which appears to be C: so I don't see how I could use that. And still, I have the absolute path of the file containing the hrefs, and the href relative paths, so since it is a simple task for me to count back the number of "....\" parts based on the absolute path of the containing file, it seems there must be a way to do this programmatically as well.
I'm hoping there's some simple method I just don't know about! Any ideas?
string exactPath = Path.GetFullPath(yourRelativePath);
works
Assuming you know the real directory the XML file lives in use Path.Combine, e.g.
var absolute_path = Path.Combine(directoryXmlLivesIn, "..\images\image.jpg");
If you want to get back the full path with any ..'s collapsed then you can use:
Path.GetFullPath((new Uri(absolute_path)).LocalPath);
This worked.
var s = Path.Combine(#"C:\some\location", #"..\other\file.txt");
s = Path.GetFullPath(s);
It`s best way for convert the Relative path to the absolute path!
string absolutePath = System.IO.Path.GetFullPath(relativePath);
You can use Path.Combine with the "base" path, then GetFullPath on the results.
string absPathContainingHrefs = GetAbsolutePath(); // Get the "base" path
string fullPath = Path.Combine(absPathContainingHrefs, #"..\..\images\image.jpg");
fullPath = Path.GetFullPath(fullPath); // Will turn the above into a proper abs path
Have you tried Server.MapPath method. Here is an example
string relative_path = "/Content/img/Upload/Reports/59/44A0446_59-1.jpg";
string absolute_path = Server.MapPath(relative_path);
//will be c:\users\.....\Content\img\Upload\Reports\59\44A0446_59-1.jpg
This worked for me.
//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat";
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);
Take a look at Path.Combine
http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx

C# - Illegal characters in path

I have a database table that containing file paths of excel files that I import using a C# script.
The script works fine unless the filepath contains spaces e.g. C:\Temp\My Excel File.xls and I get an Illegal characters in path error message. Unfortunately I am not able to change the file names at the source.
If I hard code the file path to be as below it works fine.
String Filepath = #"C:\Temp\My Excel File.xls";
How do I alter this so I can include a string variable that will store the filepath from the database e.g.
String Filepath = //Code to get FilePath from database
StringCorrectedFilePath = #+FilePath;
Thanks in advance of any help
Edit: Issue is caused by files that start with a number creating invalid escape sequence. e.g. C:\Temp\20160611 My Excel File.xls
Edit 2: SOLVED - Error was caused by carriage return characters appearing after the file extension. Please see my answer for the solution.
Whether you do this
String Filepath = #"C:\Temp\My Excel File.xls";
or this
String Filepath = "C:\\Temp\\My Excel File.xls";
the string stored in memory is just C:\Temp\My Excel File.xls, whatever the debugger may tell you. So when you read some string from somewhere (database, file, user input, ...) you don't need to "escape" backslashes. So just use that string.
Path.GetInvalidFileNameChars
FilePath = string.Concat(FilePath.Split(System.IO.Path.GetInvalidFileNameChars())).Trim();
Well you can replace blank space with %20 character and while retrieving replace back with blank space again like (you may as well choose to use regular expression for the same)
String Filepath = #"C:\Temp\My Excel File.xls";
Filepath = Filepath.Replace(" ", "%20");
While retrieving back
string mypath = pathyouhavegotfromDB.Replace("%20", " ");
I think you need to put quotation marks around the path with spaces.
string filepath = #"C:\Temp\My Excel File.xls";
filepath = $"\"{filepath}\"";
Thanks for everyone's help, I tried all of these and unfortunately they didn't work which led me to believe that the issue wasn't what I originally thought.
It turns out that the files causing the Illegal characters in path all had carriage return characters at the end of the file name, after the file extension.
To resolve this I used the following code and now it works perfectly
FilePath = FilePath.TrimEnd('\r', '\n');
Thanks everyone for your help.
Try this:
String StringCorrectedFilePath = #""+ Filepath;

Code unable to reference to local directory

The situation is like this:
I am modifying someone's code to download an image file from a shared path. So the person hardcoded the piece of code to be #"\\" + local_path
Since the call is expected to go and download from the shared path \\network\bla\bla\bla, it is fine to get hardcode in this way.
Now my problem come in, I actually need to modify some other parts and test it out in playback mode before I deliver this for actual use. However, my work guideline is not to delete away the #"\\" appended. Because, without the #"\\" the path would not link to the share directory and this changed .dll could not be used for actual activity.
Yet with this, if I were to use playback, the file path will now be \\C:\temp\Images, which will be wrong. My problem now is, how to maintain the ability of the code to link to share path and at the same time create a path local so that the code can reference to.
The UNC path \\localhost\C$\ will access the drive C: on your local computer.
The easiest solution is to simply provide a flag which indicates the type of path you want to create e.g.
public string BuildPath(bool isUnc, params string[] pathParts)
{
var path = Path.Combine(pathParts);
return isUnc ? #"\\" + path : path;
}
...
var uncPath = BuildPath(isUnc: true, "network", "bla", "bla", "bla");
var localPath = BuildPath(isUnc: false, #"C:\", "temp", "images");

C# Adding Program To Run Will Not Add Full Path

There is something weird with the way I add to registry run.
When I use
private static string AppPath = new Uri((System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).LocalPath;
to set the path in run registry it worked fine, but if folder name is "c#" for example the added key will be cut before #
so should be :
c:/desktop/c#/myprogram.exe
but it's
c:/desktop/c
What's the problem can you guys help?
I think there is an issue with the Uri escape symbols. Try this:
string AppPath = System.Reflection.Assembly.GetExecutingAssembly ().Location;
I can't duplicate what you're seeing. I think maybe you're missing some information:
var uri = new Uri("c:/desktop/c#/myprogram.exe");
string raw = uri.ToString(); // "file:///c:/desktop/c%23/myprogram.exe"
string local = uri.LocalPath; // "c:\desktop\c#\myprogram.exe"
Are you sure about what's coming out of the Codebase property there?
This happens because the # character gets encoded in the Uri and becomes %23 instead.
I'm not sure why you want to use Uri to get the location of the executable. There is a better way (as nightsnaker posted).
However, if you must use an Uri (for whatever reason), you can get the full path by doing something like this:
string s = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
Uri u = new Uri(s);
string local = u2.LocalPath+u2.Fragment.Replace('/','\\');

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

Categories