Building Content in Winform XNA - c#

I have successfully been able to build content into my winform using Winform Series 1 and Winform Series 2 but my question is, how do you get the content to be loaded back into the editor the next time you open it. The content, .xnb, file is currently being saved to a temp folder. Is there anyway to have the content be loaded back into the editor with out having to go and build each file again?
Could I just save it to the Content folder inside the bin/ folder and then look through that folder at the start up and look for .xnb files and just load them? or is there an easier way to this?

In the second WinForms sample there is a HTML readme file that describes how the application saves built content to a temporary directory and then deletes it when the program closes.
This is the important bit:
Depending on your application, you might prefer to always use the same temporary directory name, and never delete it. This will leave files lying around on your hard drive. The content build process is incremental. If your program tries to load the same content files that were already built during a previous run, you will not need to carry out any actual processing work. This can speed up loading times for programs such as level editors that are likely to want to load the same files each time they start up.
It says that deleting the temporary directory "is handled by ContentBuilder.DeleteTempDirectory, which is called by Dispose". So simply find the call to DeleteTempDirectory and remove it.
The readme file describes in more detail how the temporary directory is selected (and why). You could modify CreateTempDirectory to suit your application better. For example if your editor has "level" files, you might want to save your built content (.xnb files) in a subdirectory with the same name, next to your level, so that your game can easily open the built content.
Once your files are being kept between sessions - all you have to do is reload them. The two obvious ways are to store a list of the files that are open, and reload it next session. Or simply open everything that is in your output directory:
Here is some rough code to do the latter (assuming no subdirectories):
string folder = #"C:\TemporaryXNAFilesOrWhatever";
List<Texture2D> textures = new List<Texture2D>();
ContentManager content = new ContentManager(serviceProvider, folder);
string[] files = Directory.GetFiles(folder, "*.xnb");
foreach(string file in files)
{
string assetName = Path.GetFileNameWithoutExtension(file);
textures.Add(content.Load<Texture2D>(assetName));
}

Related

How to add or use .docx template file as a resource or reference in c#?

Im trying to make a winapp that fills the document template file using the C# form and create a new .docx file. Where should i put the .docx file and how should i use it. I placed my template inside the Debug folder and load it like:
dox.LoadFromFile("template.docx");
Im having a problem when using the executable because it doesnt seem to find the template.docx
It is possibly to have files copies into the Output Directory. This is a simple mater of setting the File up accordingly.
However, having data like this in the Programm directory is frowned upon. As of Windows XP, you are unlikely to get write access to those files anymore. So any form of changes would be blocked unless your programm runs with full Administrative Rights.
The intended place for such files are the SpecialFolders. On those you are guaranteed write rights to some degree. While you could still store the template in the programm directory to copy it there if needed, it might be better to use copy it to default user as part of hte setup process.
Of course Visual Studio loves to run code under rather odd user accounts. So I am not sure how far that works for testing.
You can store you word document directly in your assembly (juste copy past the file in your project).
Then you just copy it to windows temp folder before doing your own business. Just don't forget to delete the file in the temp folder when you are good because windows won't do it for you.
Dim fileLocation As String = Path.GetTempFileName()
Using newFile As Stream = New FileStream(fileLocation, FileMode.Create)
Assembly.GetExecutingAssembly().GetManifestResourceStream("YourAssemblyName.yourfile.docx").CopyTo(newFile)
End Using
...
System.IO.File.Delete(fileLocation)

How to determine path of resource files on different computers? - C#

I am writing a simple game for my course work. The application contains many pictureboxes with no images inside them. I also have a directory with needed pictures in the Visual Studio project debug folder. I need to put the pictures' paths into an array in my program to then randomly insert them into pictureboxes.
The problem is I don't know how it would work on another computer, so I can't organize all the things. The game must be launched without using Visual Studio there, only exe file. Should I first make the installation setup of my unfinished program, or something like this, and then place the application with resources somewhere on disk to know where all my pictures would be on any computer? And then maybe I could determine the exact path where I would take all the pictures and put them into the array. Or vice versa... I'm totally confused with this.
Here what I use to fill the array:
string[] spritePaths = Directory.GetFiles(/*paths*/);
Is it possible for you to distribute the pictures in a folder with the .exe file? If so, you could use a relative path to get all of the pictures.
string[] spritePaths = Directory.GetFiles("pictureFolder");
As DangerZone suggests, you could also add your images as embedded resources.
https://support.microsoft.com/en-us/help/319292/how-to-embed-and-access-resources-by-using-visual-c
Here are a few options:
Specify the path to the folder of images as a command line argument. Then you can launch it from CMD, or create a shortcut and specify the arguments there.
Add a TextBox for the user to enter the path to the images.
Add a browse button or menu button and allow the user to search for the folder using a dialog.
Use a predefined location, such as an images folder next to the exe.

How to save a file's original location?

This is what i'm trying to do in my application:
On startup, the application searches for specific files (*.txt for example) in a specific folder (let's say c:\testfolder + all subfolders) and stores their path in a simple string[]. Some files might be located in the root-folder (c:\testfolder), some files have additional subfolders (c:\testfolder\subfolderA\subfolderB).
Now, when I click on a button, all selected files are moved to a temp-folder (like c:\testfolder\temp). When I now close and reopen the application, I want to move all files from the temp-folder to their original location. Obviously this won't work, since the original path was overwritten after restarting the app.
This might be an easy task, but could someone maybe give me hint on how I could do this?
/edit
Would it be possible to ignore a specific folder (temp-folder in this case) when searching for files? Basically moved files are ignored & the old path is still saved (in Properties.Settings. for example) from the first start.
Current code I'm using to get all files:
var files = Directory.EnumerateFiles(file_path, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".jpg") || s.EndsWith(".png"));

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