i am new to c#. if i have a file in ProjectFolder\file.txt, how can i access it in code. eg. i want to read a file in code. i remember the path looks like application://.../file.txt but i cant remember how exactly
Just set your Copy to Output Directory property of your file to Copy if newer:
When you run your program from the output directory, you can simply open the file from the current directory:
string text = File.ReadAllText("file1.txt");
Most people's solutions refer to accessing a file on your file system. However, you mentioned application local URIs, which made me think you are talking about embedded resources. Those resources aren't a separate file on your filesystem. So, the rest of my post is about that.
If you would like to include the file in your assembly, you have to change the properties on the file, changing the BuildAction property to Embedded Resource.
From there, you can access it with the resource path, as you described (see Pack URIs: http://msdn.microsoft.com/en-us/library/aa970069.aspx), or you can access it this way:
var stream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream("ConsoleApplication1.blah.txt");
var reader = new StreamReader(stream);
Console.WriteLine(reader.ReadToEnd());
Related
I need to make a program that reads the columns of an excel. But for that, I need to get the path (directory) of this excel. What prevents me from doing this, is that I didn't want to leave my local directory fixed, because if someone downloads the file on another machine, they will need to change the path.
You asked How to get directory of an xls file C#.
As others have pointed out, the file needs to be in a known location and one way to do that is to add the Excel file to your solution and mark it as Content, specifying that it should be copied to the output directory. The image below shows how to set these properties.
You also seem to be looking for a robust way to make this happen when you deploy the app for other users. For this, you will need a strategy for making an .msi or .msix that will place this file where it needs to be. But to answer your basic question the way you asked it the path in this case can be obtained in this manner. This code will get the path and open the Excel file.
// Get the path and open the Excel file
static void Main(string[] args)
{
var path =
Path.Combine(
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
"Microsoft Excel Worksheet.xlsx");
Console.WriteLine(path);
System.Diagnostics.Process.Start("explorer.exe", path);
}
I should mention that a file in the executing directory can be read but not written (without elevated permissions). If the file is user data then refer to the answer that uses an Environment variable:
var appdata = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
You have two options:
If you don't want to your excel files to be stored in your application's directory, you can simply put things in the root of your C: partition. Every windows device is gonna have the C: partition. As the user Lee Taylor has pointed out, it turns out you can have a windows device without the C: partition, although uncommon
If you don't mind having your excel files stored in your application's directory, you can get the relative path of your application's directory throughPath.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
There are other ways but I believe these are the simplest and easiest to do.
If you just need to dynamically get the path to a file that is in the same project directory, then the following code works for me -
string filePath = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "\\excel\\Prices.xlsx";
where "\excel" is the folder in my project and "\Prices.xlsx" the file in the project
I have a Settings.settings file which contains a number of different endpoints in it. I want to embed this file into the .dll file so users cannot view or modify the endpoints.
Under the Build Action option for the Settings.settings file I see Embedded Resource. I read through the MSDN page here, but I'm still not entirely sure this is the option I want.
Can anyone confirm this does what I want it to, and if not, which option should I select?
I use the embedded build action for storing a Word doc template, but I don't see why you couldn't use it for something else such as an XML file that contains all your settings. Set your build action to embedded and you can reference it as such:
var template = "filename.xml" // <-- this is the file you mark to be embedded
Assembly loader = Assembly.GetExecutingAssembly();
var rawstream = loader.GetManifestResourceStream(template);
byte[] byteArray = rawstream.ReadToEnd();
You will need this using statement:
using System.Reflection;
Not exactly what you asked, but there's another way.
Specify your settings in your web.config or app.config file. Then encrypt the config file when you deploy.
See this link:
http://msdn.microsoft.com/en-us/library/zhhddkxy(v=vs.100).aspx
how can i bring my files (located in resources) back to life. This means every time my program launches, it will delete everything in its directory except it self, then extract those files . I want those files to be created in the currentdirectory.
Can u provide a concept how to extract the files in directory. Then delete everything when it the program starts again,
PS: those files end in .ovpn (they are not binary because they can be read in notepad.. how can i make those files .ovpn in the filesystem?
Tnx
To get a file compiled as an embedded resource you can do this:
using (var stream = Assembly.GetCallingAssembly()
.GetManifestResourceStream("Namespace.FileName.Extension"))
{
// write file...
}
Of course you would need to use the assembly that the resource resides in.
So for a file called 'Help.txt' in namespace 'MyCompany.MyProduct' you would call:
GetManifestResourceStream("MyCompany.MyProduct.Help.txt")
Hope that gets you on your way.
I have a Silverlight 4 / C# project I'm working on in Visual Studio. I made an XML data file by right clicking on the project >> Add New Item >> Xml File. I then try to open the file:
StreamReader streamReader = new StreamReader("data.xml");
However, this gives a security exception. How can I get around this, or grant the necessary permissions?
Silverlight doesn't allow local file system access by default. Your options are:
Using IsolatedStorage.
Run with elevated permissions.
Embedding the file in the assembly, if you only need to read it, as suggested by Jon Skeet.
If you need to store data in general, use IsolatedStorage if you can.
You would need to mark the item as a resource, NOT an embedded resource.
From MSDN...
The Properties window in Visual Studio
provides several other values in the
Build Action drop-down list. However,
you can use only the previous three
values with Silverlight projects. In
particular, Silverlight embedded
resources must always use the Resource
build action, and not the Embedded
Resource build action, which uses a
format that Silverlight cannot
recognize.
A great walk through can be seen here entailing what you are trying to accomplish. Since you are not trying to access files on disk but as resources this is not a problem. IsolatedStorage nor elevated permissions are pertinent here.
Do you just need to be able to read the file at execution time? If so, I would suggest you set it to have a Resource build action in Visual Studio, and then use Assembly.GetManifestResourceStream to open it. That's the simplest way of bundling read-only data with an application, IMO.
That constructor of StreamReader is expecting a file path into the local file system, which is only available out of browser with elevated trust.
Instead you should be using Application.GetResourceStream:-
Stream stream = Application.GetResourceStream(new Uri("data.xml", UriKind.Relative));
StreamReader reader = new StreamReader(stream);
However I expect you really just want this in an XDocument, you bypass this StreamReader stage:-
XDocument doc = XDocument.Load(stream);
BTW, I personally would leave the XML as Content in the Xap rather than embedding it in the assembly.
I've added a resource file to my project called CrpResource.resx .
Then, after adding a text file to the resource file, I wanna to access to it and read from it by code.
any suggestion please.
#Brij has provided the core of the answer.
However, the difficult bit here is knowing what the resource name is - it's not always easy after embedding a file as a resource to work out its fully qualified name.
An easy way to find out is to add this line temporarily to your code:
string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames();
Then run the program, and you can view the 'names' list of all available resources in the debugger.
_assembly = Assembly.GetExecutingAssembly();
_textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("MyNamespace.MyTextFile.txt"));
See following:
http://support.microsoft.com/kb/319292