I have to include some files with my windows phone 8 app. the app will accordingly get those file from resource and read or show partly the content according to the algorithm. how do i get the path to my embedded resource?
If you include file in you project, for instance in Data folder of your project (in our case json file) as a resource then use next code to get content from that file:
string content = string.Empty;
string resource_file = "Data/myfile.json";
if (IsLocalResourceFileExists(resource_file))
{
var resource = Application.GetResourceStream(new Uri(#"/YourProjectName;component/" + resource_file, UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream, System.Text.Encoding.UTF8);
content = streamReader.ReadToEnd();
streamReader.Close();
}
To check if file exist in resource use this:
public bool IsLocalResourceFileExists(string relativePath)
{
return Application.GetResourceStream(new Uri(#"/YourProjectName;component/" + relativePath, UriKind.Relative)) != null;
}
Change YourProjectName to name of you project.
After this, conten holds json file as string.
Hope this help
Related
Is it possible to attach a text file resource to my Winform exe. So when I run the "Form.exe" in another computer then it copy the text file to a specified folder. Please suggest a method to achieve the same. Thanks
If the resource name is a string:
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream(resourceName))
using (var reader = new StreamReader(stream))
{
string text = reader.ReadToEnd();
File.WriteAllText(fileName, text);
}
else:
File.WriteAllText(fileName, Properties.Resources.TextFile1);
And also make sure that you have set the Build Action of the resource file to "Embedded Resource".
First you need to add your file as a resource in your project.
This explains what to do
Then select your file and in the properties change the "Build Action" to "Embedded Resource". This will now embed your file in your output (.exe).
To extract the file you need to do the following;
String myProject = "Name of your project";
String file = "Name of your file to extract";
String outputPath = #"c:\path\to\your\output";
using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(myProject + ".Resources." + file))
{
using (System.IO.FileStream fileStream = new System.IO.FileStream(outputPath + "\\" + file, System.IO.FileMode.Create))
{
for (int i = 0; i < stream.Length; i++)
{
fileStream.WriteByte((byte)stream.ReadByte());
}
fileStream.Close();
}
}
Ideally you should check that the file does not already exist before you do this. Don't forget also to catch exceptions. Which can be very common when dealing with the file system.
Add the text file to your project resources
Properties -> Resources -> Add Resource
Read the data from the resource using
var text = Properties.Resources.textFile;
Write to the file with
File.WriteAllText(#"C:\test\testOut.txt", text);
I use Visual Studio 2015 with Xamarin Android.
I want to read some JSON data from file, but I keep getting this System.IO.FileNotFoundException, even though I have set my files properties "Build: Content, Copy to Output Directory: Copy if newer" and I can see the file physically in my build folder.
I use this code:
var path = #"AedJson.json";
using (var streamReader = new StreamReader(path))
{
string json = streamReader.ReadToEnd();
//JObject o1 = JObject.Parse(json);
}
The exact exception is:
System.IO.FileNotFoundException: Could not find file "/AedJson.json".
Error Picture
You need to add your json file to your Xamarin.Android project as an Asset (within the Assets folder) and flag it as an AndroidAsset build type, then you can use the AssetManager to read it.
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader (assets.Open ("AedJson.json")))
{
string json = sr.ReadToEnd ();
}
Ref: Using Android Assets
I'm not sure it really is an error, but looking at the error, it seems like the path is incorrect. Do you really need to save your file precisely where you're actually saving it ? If not, try this :
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "myfile.txt");
using (var streamReader = new StreamReader(filename))
{
string json = streamReader.ReadToEnd();
//JObject o1 = JObject.Parse(json);
}
Use this path to save and to load. I'm proceeding like this for all my files and it seems to work well.
This works using Microsoft.Extensions.Configuration.Json
Set json file build action in properties as embedded resource
Project : Client
FileFolder : Configuration
FileName : appsettings.json
JSON :
{
"Rest": {
"Server": "192.168.0.199",
"Port": "5003"
}
}
CODE:
string Namespace = "Client.Configuration";
string FileName = "appsettings.json";
Assembly assembly = GetType().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{Namespace}.{FileName}");
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonStream(stream);
var root = configurationBuilder.Build();
IConfigurationSection restClientConfigration = root.GetSection("Rest");
string server = restClientConfigration.GetSection("Server").Value;
string port = restClientConfigration.GetSection("Port").Value;
I have a C# project name as ("Test") which has a class and a folder contains a html file and my senior has compile this project into a dll.
the content of the html file is = "Hello World"
the class contains :
string that read the whole html file.
context.Respone.Write(the string above).
I have another web project which has a page to call the method above by adding the test dll. The question is, how can I read the content of the html file by getting it from the dll ? So that the web page can display "Hello World"
Put your file in Embedded resource and read it using code liek that
public static string GetResourceFileContentAsString(string fileName)
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "Your.Namespace." + fileName;
string resource = null;
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream))
{
resource = reader.ReadToEnd();
}
}
return resource;
}
I have a folder called data/ in my project that contains txt files.
I configured Build Action to resources to all files.
I tried these different ways:
method 1
var resource = Application.GetResourceStream(new Uri(fName, UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
Debug.WriteLine(streamReader.ReadToEnd());
method 2
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
string[] fileNames = myIsolatedStorage.GetFileNames("*.txt");
method 3
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamReader fileReader = new StreamReader(new IsolatedStorageFileStream(fName, FileMode.Open, isf)))
{
while (!fileReader.EndOfStream)
{
string line = fileReader.ReadLine();
al.Add(line);
Debug.WriteLine(line);
}
}
}
Now, i tried different ways to read files without success, why?
Where is the problem?
What's wrong with these methods?
fName is the name of the file.
It's necessary the full path data/filename.txt? It's indifferent...
please help me with this stupid issue,
thanks.
Your 2nd & 3rd approaches are wrong. When you include a text file locally in your app, you can't refer it via the IS. Instead, use this function, it will return the file content if found else it will return "null". It works for me, hope it works for you.
Note, if the file is set as content, the filePath = "data/filename.txt" but if it is set as resource it should be referred like this filePath = "/ProjectName;component/data/filename.txt". That may be why your 1st approach might have failed.
private string ReadFile(string filePath)
{
//this verse is loaded for the first time so fill it from the text file
var ResrouceStream = Application.GetResourceStream(new Uri(filePath, UriKind.Relative));
if (ResrouceStream != null)
{
Stream myFileStream = ResrouceStream.Stream;
if (myFileStream.CanRead)
{
StreamReader myStreamReader = new StreamReader(myFileStream);
//read the content here
return myStreamReader.ReadToEnd();
}
}
return "NULL";
}
How can I read from an embedded XML file - an XML file that is part of a c# project?
I've added a XML file to my project and I want to read from it. I want the XML file to compile with the project because I don't want that it will be a resource which the user can see.
Any idea?
Make sure the XML file is part of your .csproj project. (If you can see it in the solution explorer, you're good.)
Set the "Build Action" property for the XML file to "Embedded Resource".
Use the following code to retrieve the file contents at runtime:
public string GetResourceTextFile(string filename)
{
string result = string.Empty;
using (Stream stream = this.GetType().Assembly.
GetManifestResourceStream("assembly.folder."+filename))
{
using (StreamReader sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
}
}
return result;
}
Whenever you want to read the file contents, just use
string fileContents = GetResourceTextFile("myXmlDoc.xml");
Note that "assembly.folder" should be replaced with the project name and folder containing the resource file.
Update
Actually, assembly.folder should be replaced by the namespace in which a class created in the same folder as the XML file would have by default. This is typically defaultNamespace.folder0.folder1.folder2......
You can also add the XML file as a Resource and then address its contents with Resources.YourXMLFilesResourceName (as a string, i.e. using a StringReader).
Set the Build Action to Embedded Resource, then write the following:
using (Stream stream = typeof(MyClass).Assembly.GetManifestResourceStream("MyNameSpace.Something.xml")) {
//Read the stream
}
You can use Reflector (free from http://www.red-gate.com/products/reflector/) to find the path to the embedded XML file.
Then, it's just a matter of
Assembly a = typeof(Assembly.Namespace.Class).Assembly;
Stream s = a.GetManifestResourceStream("Assembly.Namespace.Path.To.File.xml");
XmlDocument mappingFile = new XmlDocument();
mappingFile.Load(s);
s.Close();
Add the file to the project.
Set the "Build Action" property to "Embedded Resource".
Access it this way:
GetType().Module.Assembly.GetManifestResourceStream("namespace.folder.file.ext")
Notice that the resource name string is the name of the file,
including extension, preceded by the default namespace of the project.
If the resource is inside a folder, you also have to include it in the
string.
(from http://www.dotnet247.com/247reference/msgs/1/5704.aspx, but I used it pesonally)
#3Dave really helped (up vote given), however my resource helper was in a different assembly so I did the below
public string GetResourceFileText(string filename, string assemblyName)
{
string result = string.Empty;
using (Stream stream =
System.Reflection.Assembly.Load(assemblyName).GetManifestResourceStream($"{assemblyName}.{filename}"))
{
using (StreamReader sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
}
}
return result;
}
Called by
GetResourceFileText("YourFileNameHere.ext", Assembly.GetExecutingAssembly().GetName().Name);