Loading file in silverlight - c#

I would like to load a custom file put as a resource file in my silverlight application, but the FileStream doesn't works (since I must stay in a partial trust environnment).
Is there any solution to load my file? (it is a binary serialized data).
UPDATE
Answer found :
I put my file as a "Resource" (not embedded neither content or anything else)
Loaded it like this :
StreamResourceInfo info = Application.GetResourceStream(new Uri(#"/Utilitaires;component/Resources/" + name, UriKind.Relative));
And then using the "info.Stream" property.
Now, I have an other asking. By doing like this, the file is added to the assembly (to the exe/dll), and make it a bit bigger.
But since these datas need to be loaded at the same time as the assembly, should I let them as a resource, or use another method to load them separatly? (and what should be the method? I need it to work in local as well as on a server).
Thanks,
KiTe

Since you need the resource at the same time as you load the assembly then the only other reason to place the file outside the Xap would be to allow the file to be modified without modifying the Xap.
Personally I would include the file as "Content" rather than "Resource". This means that the file ends up as an entry in the Xap (which is just a Zip file) rather than inside a dll.
You still use GetResourceStream to access it but the Url becomes something like:-
new Uri(#"/Assets/" + name, UriKind.Relative)
Where Assets is a folder you create in your project to store additional files, also name should include a file extension.
Using this approach kind of gives you the best of both worlds. The file is included in the Xap but if for some reason the file content needs to be modified the Xap can be opened as a Zip file and the file replaced.

Related

Embedded Resource Name Loses Extension When File is Nested

I have some scripts stored in files that I've marked as Embedded Resource. I nest each of these files under their associated .cs file. Unfortunately, for some reason, when you nest a file this way, the embedded resource name loses the file extension. This means that at runtime I have no way to identify which embedded resources are or aren't scripts. What can I do about this?
One thing I tried that did not work: getting the ManifestResourceInfo object, which has a FileName property. Unfortunately this property is null.
Another thing I tried was doubling up the extension. (like: filename.ext.ext). This didn't work, and everything after the first . is still missing.
I tried naming the resource with something very different, and noticed that the resource name didn't even change. It seems that it is generating the resource name for a nested embedded resource file based off of the "dependent upon" file, which in this case is just a regular .cs file. I tried doubling the extension of the .cs file to filename.extrastuff.cs but the resource name still doesn't change. It insists on clipping everything after the first ..
No, ok, I see now that it is actually naming the resource after the type defined in the .cs file, not the filename of either file. This is why the extension makes no difference. This means there is nothing I can do to either filename to help find the resource.
I discovered that the reason the file loses its extension is because for some reason when the file is nested, VS is naming the resource after the type instead of after the file.
The only thing I've found to allow me to still have an extension when nesting is to manually edit the .csproj file and add a LogicalName tag, which allows you to override the resource name.
<EmbeddedResource Include="Path\To\NestedFile.ext">
<LogicalName>NestedFile.ext</LogicalName>
<DependentUpon>ParentFile.cs</DependentUpon>
</EmbeddedResource>
Unfortunately, there is no IDE support for this, and the FileNesting extension I'm using doesn't support writing this tag either.
It's too cumbersome to have to do this for every file, so instead of relying on the file extension, I would have to do something like add an identifier inside my script files that identifies them as scripts.
Ultimately I realized that since in my case I'm validating script files from unit tests, I can simply scan the file system instead of the resource manifest and avoid this problem altogether.

Download File without giving Folder Name

In my project , i have a download button in jqgrid. When I click this button the appropriate file must be downloaded, but here is my problem; all these files come from different folders, so I cannot set a folder name in mappath. I saw different code for downloading, but in every case there has to be a folder name.
I have gound one solution for this; to bind the folder name & file name in a grid ,but there is a huge amount of data and I cannot change the database.
My question is: how can I download a file without a giving folder name?
but here my problem is all these files come different folders, so i
cannot give folder name in mappath
you can't download a file without knowing the virtual or absolute path. In your case, you want to download a file, but certainly (your code)doesn't know where it resides. more accurately, your code doesn't have a clue to provide the path of the file.
You should be able to provide a mechanism to down the file(be it keeping the file path in a DB table or a mapping of user to folder), you wont get a generic solution to your issue.

c# writing to a file without full path

If I use this code
File.AppendAllText("C:/Users/Michael/Documents/Visual Studio 2010/Projects/PuzzleGame/PuzzleGame/PuzzleGameContent/player.TXT", "hi");
The file will save and add "hi" to the end of it. However, if I do something like this:
File.AppendAllText("player.TXT", "what is good?");
The file won't have a "what is good?" at the end of it. I can read files just fine using only the "player.TXT" filename but I can't write to a file using only that. Can anyone help me?
Your working directory is wherever the .exe is (unless you change it). So you see, when you compile, the exe ends up in the bin folder, so your player.txt would need to be there, not with your source.
edit:
I bet you're appending to player.txt THEN you read it and that's why it worked fine, because you created a new one in your bin folder. Otherwise, read would not have worked. If you go in your bin folder and delete player.txt, your readfile shouldn't work.
Both forms are perfectly valid. The likely scenario is that your second version is simply writing to a file at a different location, because not specifying the path will default to the current directory.
If you don't include a path, you'll want to ensure the current directory is valid for accessing the file.
Most likely there are two files on the file system, one in the directory that is explicitly defined in the first example and one where the executable is running in the second example since no explicit path was defined in the parameter of the method call.
From MSDN:
Given a string and a file path, this method opens the specified file,
appends the string to the end of the file, and then closes the file.
The file handle is guaranteed to be closed by this method, even if
exceptions are raised.
The method creates the file if it doesn’t exist, but it doesn't create
new directories. Therefore, the value of the path parameter must
contain existing directories
.
The problem is that AppendAllText is a method which will create the file if it doesn't already exist. So when you use an incomplete path it is unsure whether to create a new file in a base directory or add to an already existing file. If you can't use the full path for whatever reason, you could get the current working directory using something like:
File.AppendAllText(System.Environment.CurrentDirectory + "player.TXT", "what is good?");
So long as the current directory is correct, it'll work the same as your first working example.

How to implement a text file in content (XNA)

I am building a game which loads its map from a text file.
While creating the parts that handle maps, I simply kept the text file in the content folder and fetched it by its Windows filepath. This won't work for proper deployment (or even running the game from different drives) because it requires that the filepath be exactly the same.
I looked around for a way to include the text file the same way I would a Texture2D, but I cannot find any class that allows me to use it. Some answers to other questions suggested that I just use the text file from my content folder? How would I do that? My program's name is IslandQuest (placeholder; it doesn't even involve an island) so would I place the text file in the IslandQuestContent folder generated by XNA Studio? How would I access it from there such that its filepath doesn't depend on the drive configuration of a computer?
Thanks for any help.
This may not be the best way to do this but just looked back at what I did in my first year at university with XNA,
I added my txt file to the contents folder. Then in the properties for the file (select it in the solution explorer and view properties window) there should be "Copy to Output Directory", make sure this is copy if newer.
Then its just a case of
string.Format("Content/{0}.txt", filename)
I do think this can be improved perhaps by the following but it is untested
Path.Combine(Content,filename +".txt");
In my case I was reading XML file files from a data folder in my main project.
So under my project in Solution explore I had this set up:
WindowsPhoneGame1
...
data/
content.xml
Game1.cs
Program.cs
etc...
Where properties for content.xml were Build Action: Content and Copy to Output Directory: Copy always
In the class that read the file I used TitleContainer.OpenStream Method which according to the docs:
Returns a stream to an existing file in the default title storage
location. .... The stream returned is read-only. The file to be read must already exist, or this method will fail.
My example code
//open stream
Stream stream = TitleContainer.OpenStream("data/content.xml");
//do something with it...
Create a "Content" folder in your main project.
Put the files that cannot be put in the Content project in there.
Be sure to set all your content Build actions to Content and Copy Always.
The Content folder from your main project and the content in the content project will end up in the same folder when built.
The file path would still be "Content/file.ext" or whatever.

c# - where to place txt files

I'm working on a simple progam, and part of it populates a list from a txt file.
this probably is not a smart question but, I didn't find any info on this.
I was wondering where is the best place to put text files in the application directory.
O know about the Resouces but, I wasn't able to get the path of the file I stored there.
so 2 questions:
where is the best place to put a txt file? (or any other importent file to use in the application)
if I put files in the Resources how do I get its path ?
(sorry fo my English)
If these are files that you do not need to expose to the users and only serve an internal purpose, then you can embed them in your assembly as resources, and extract them when you need them.
To do this, create a new directory in your application. Let's call it 'Resources'. Then, add text files to it. Use the properties window of each text file to change the BuildAction setting to "Embedded Resource". Then, in your code once you need the contents of the file you can use code like this to extract it:
using System.Reflection;
// ...
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyApplication.Resources.MyFile.txt")) {
using (StreamReader reader = new StreamReader(stream)) {
string contents = reader.ReadToEnd();
// Do stuff with the text here
}
}
If you don't want to do this, the correct location to place files is in a directory you create under the AppData directory. This is a known system path, which you can obtain like this:
string folderLocation = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string myPath = Path.Combine(folderLocation, "MyAppName");
You can then use a StreamReader or other class in System.IO to find/enumerate and read the files.
When an application has associated/companion data files it sometimes makes sense to embed them as a Resource, because then there is less chance for them to be tampered with e.g. deleted, or the data modified.
And other times it makes sense to keep the file loose....so you have to decide the best place to store them....you can locate these in the place where the application is installed, or in the Application Data/AppData directory.
For embedding files in Resources have a look at this link:
http://support.microsoft.com/kb/319292
It has a step-by-step guide showing how to embed a file (e.g. a Text file into Resources), and then using a StreamReader to access it and read its contents.
To store the files and access them from a suitably located directory you can use:
System.Environment.SpecialFolder.ApplicationData
with
Environment.GetFolderPath()
to find out where the AppData directory is.
Then when you create your application Setup/Installer, you should get it to create a directory for your application underneath AppData, and then you can decide what files you want to be installed into that location.
See:
Saving a file to Application Data in c#
Note, ApplicationData "roams"...i.e. when you logon to a different machine, the files are transferred onto that machine as part of your profile....you may not want this....so you could instead use:
System.Environment.SpecialFolder.CommonApplicationData

Categories