Reading a file added manually in project as resource in VisualStudio - c#

In my soloution, for one of the projects I have to add a binary file and read its content in the form_load event.
As you can see in the picture I have added it to the appropriate project and have set the Build Action to Content and Copy to Output Directory as Copy Always.
Now can somone please tell me how how to access this file?
private void SetupForm_Load(object sender, EventArgs e)
{
//Find the path to file then
//READ THE FILE
}

Now you should find this file in your output directory after building your project. Given the right path to the file, you can access this file with any method you want.
Some methods can help you to get the path to the file:
Directory.GetCurrentDirectory();
Environment.CurrentDirectory

I'm not sure exactly what you're trying to do with the file, and that will determine your best approach here. As per the answer here you have a couple of options. To paraphrase:
Serialization
Binary Reader

I think the best method was this, so far:
So when I add the file to the project, it will be in the same folder as the exetubale file of project resides. So for getting the path (including the name of exetuable file I had to use Application.ExecutablePath and to remove the file name and have the pure path to the folder I had to use Path.GetDirectoryName() and finally add the filename I wanted to acces to this path, as you can see below:
var path = Path.GetDirectoryName(Application.ExecutablePath) + "\\YourFileName.bin";

The API you call to read the file depends upon the type of file. But the general pattern is like this.
private void SetupForm_Load(object sender, EventArgs e)
{
System.IO.Stream input = Application.GetResourceStream(new Uri #"/MyApp;component/content.bin", UriKind.Relative)).Stream;
BinaryReader binaryReader = new BinaryReader(input);
}

You can directly readbytes from the file attached as resource.My resource in this example is SampleWordnew document.
byte[] bob = ReadBytesfromResources.Properties.Resources.SampleWordnew ;

Related

cannot find the path to the resource file c#

firstly apology if this has already been answered and I am duplicating the question. I have tried to find the answer to my issue but have failed and none of the auto-suggestions answers my problem.
I have my main project (XAML) and also a class library project called FileStore for files. The class library project is referenced into the main project and I have images and icon file in the class library project that I can access with no issues in my main project, however, I struggle to get the content of a txt file from the CL project to display in a label on the main project. I get the error: the system could not find the file and from the error, I can see that it is trying to look for a file in the main project bin\debug folder
I tried to follow this previous post which seemed to partly answer my issue but to no avail sadly.
Get relative file path in a class library project that is being referenced by a web project
The txt file Build action is set to: Resource and Copy to Output Directory set to: Copy Always.
As I mentioned I have the FileStore project referenced in my main project and the images work fine.
Below is the code I am using, I have tried different variations such as:
\Resources\textFile.txt and \textFile.txt, still no luck.
'''
public static string ReadFileinClLibr()
{
var buildDir =
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var filePath = buildDir + #"\textFile.txt";
return File.ReadAllText(filePath);
}
'''
For comparition here is the path for the image files that works, but I cannot get it to work with the txt file, as the error reads: the given paths format is not supported..
'''
#"pack://application:,,,/FileStore;component/Resources\textFile.txt"
'''
I want to be able to input the content of the text file from the class library project to the label in the main xaml project.
At the moment compiler keeps looking for this file in a debug folder of the main project, what I want is, for the compiler to look for the txt file in a CL FileStore project
In order to access the file all the time, we have to have the file copied to the debug folder. Right click the file from solution explorer change the properties then try to access the file from the executing assembly location.
StringBuilder bodyContent = new StringBuilder();
string fileName = "myfile.txt";
try
{
string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName);
using (StreamReader sr = new StreamReader(filePath))
{
// Read the stream.
bodyContent.Append(sr.ReadToEnd());
}
}
catch(Exception ex)
{
Console.WriteLine(String.Format("{0} # {1}", "Exception while reading the file: " + ex.InnerException.Message, DateTime.Now));
throw ex;
}
Thanks to the post from #Sreekanth Gundlapally I have managed to fix my issues. I have mostly drawn on from the answer provided by #Sreekanth Gundlapally but there is one important bit missing. The string fileName should include any subfolders that the resource file is within in the Class Library Project, for example in my case the folder was named 'Resources' so the code should look like this:
string fileName = #"Resources/myfile.txt";
try
{
string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName);
using (StreamReader sr = new StreamReader(filePath))
{
// Read the stream.
bodyContent.Append(sr.ReadToEnd());
}
I have also cleaned and rebuilt solution after which it all worked a charm.
Also a side note, anyone trying this and getting funny characters make sure your file's encoding is set to UTF-8 as this is the default encoding used by StreamReader, otherwise your file content may not be read correctly if it contains signs such as apostrophe.

C#: Writing a RTF (Text) file to system drive

I have a program which contains a richTextBox and a Button. Upon clicking the button, the program gets the text from richTextBox and saves it to a predefined location stored in a string variable.
If I change this location to C drive which is my System Drive, it won't allow me to do it and throws a System.UnauthorizedAccessException.
I am also the admininstrator of my PC. Is there any way that I can get permissions or work something out to solve this issue? Thanks in advance.
I use the following code
private void button1_Click(object sender, EventArgs e)
{
string temp = location;
System.IO.StreamWriter file = new System.IO.StreamWriter(temp);
file.WriteLine(this.richTextBox1.Rtf);
file.Close();
}
Trying to write files directly to the root of the c: drive often cause problems, such as the exception you're seeing.
Try storing your file somewhere else. A good way of getting a safe folder is to use the SpecialFolder enumeration: (change it to Desktop, MyDocuments, or whatever might be appropriate in your case)
string temp
= Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "myFile.txt")
System.IO.StreamWriter file = new System.IO.StreamWriter(temp);
Considering your update, try this instead:
string temp
= Path.Combine(#"C:\Users\MuhammadWaqas\SkyDrive", "myFile.txt");
As pcnThird suggested, you could save it to "myFile.rtf" instead and take advantage of the file type, assuming you're going to be opening the file and reading the contents outside of your app.
You have to specify a file name instead of a folder, try changing location to "C:\Users\MuhammadWaqas\SkyDrive\test.txt"
Check your location. You might be trying to write to a non existent or restricted location

Access to Resources

I've C# project and it has Resources folder. This folder has some of txt files. This files have various file names.
I'm taking file names from any source as string variable. For example I have fileName string variable and test.txt file in Resources folder:
string fileName = "test.txt";
When I want to access this file as like below, I can:
WpfApplication.Properties.test.txt;
But, When I want to access it by this code, I can't.
WpfApplication.Properties.fileName;
I want to use fileName string variable and access this text file.
What can I do to access it?
Thanks in advance.
Edit :
I change form of this question:
I've string variable assigned any text file name. For example; I have a.txt, b.txt, c.txt, d.txt, etc.. I'm taking this file name as string variable (fileName) via some loops. So, I took "c.txt" string. And, I can access this file by code in below:
textName = "c.txt";
fileName = "../../Resources\\" + textName;
However, when I build this project as Setup Project and install .exe file to any PC, there is no "Resources" folder in application's folder. So,
../../Resources\
is unavailable.
How can I access Resources folder from exe file's folder?
You need to add a Resource File to your project wich has the extension .resx/.aspx.resx. You will then be able to double click on this file and edit the required resources/resource strings. To do this right click on Project node in Solution Explorer > Add > New Item > Resource File. Let us assume you have added a file called ResourceStrings.resx to the Properties folder and added a resource string with key name MyResourceString, to access these strings you would do
string s = Properties.ResourceStrings.MyResourceString;
I hope this helps.
I would strongly recommend you taking a look at: http://msdn.microsoft.com/en-us/library/aa970494.aspx
If your text files have build action set as Resource you can locate them in code like:
(assuming the file name is fileName and its located in Resources folder)
Uri uri = new Uri(string.Format("Resources/{0}", fileName), UriKind.Relative);
System.Windows.Resources.StreamResourceInfo info = Application.GetResourceStream(uri);
Then you can access info.Stream to get access to your file.

Saving file in folder and path in database

I want to save image into a folder and the path of the folder to the database.
I have done this with File.Copy(filepath) command but it is giving me error when a file with the same name already exists there.
Second thing in this command is that I have to provide a filename in it from which it is copying the file. If I am modifying a record and not the image then it is giving error that file source cannot be empty.
I have also tried Picture1.image.save(filename) but I have not found any command to overwrite the existing file.
Please help me by providing a simplest way to do all this.
There's an overload to the File.Copy() method that accepts a bool which will determine whether to overwrite any existing files with the same name.
http://msdn.microsoft.com/en-us/library/9706cfs5.aspx
File.Copy(sourceFileName, destFileName, true) Will force an overwrite of existing file.
Refer MSDN File.Copy
if(File.Exists(destinationFileName))
{
File.Delete(destinationFileName);
}
File.Copy(sourceFileName, destinationFileName);
sourceFileName shoudl be the full path of the source file(including the file name).
destinationFileName should be the fullpath (including the filename) where you want to save the file.
you have to first check whether file exists or not?
using FileInfo,
FileInfo file = new FileInfo(location);
if(file.Exists())
{
File.Delete(location);
File.Copy(srcLocation, location);
}
In this way you can avoid the error.

How to delete 0KB text file

1) I am new to c sharp,
I am having a problem ,
I know how to delete the file,
I am using this line of code to delete the file,
private void button2_Click(object sender, EventArgs e)
{
File.Delete(a);
}
I want to know how to delete 0KB file.
2)and one more thing i want to know how many path we can save for our application like ,
private void button2_Click(object sender, EventArgs e)
{
String a = (String)(Application.StartupPath + "\\TEMP");
}
I think there are more paths like Application.StartupPath ,can anyone pls say how many ways are there to save a path like Application.StartupPath .
There would be a great appreciation if someone could help me,
Thanks in Advance,
You delete a 0KB file just like you delete any other file (i.e., File.Delete is correct). If the file cannot be deleted, it is probably in use. You can use Process Monitor to find out which process is using the file.
Other special paths can be obtained using Environment.GetFolderPath with the SpecialFolder enumeration.
EDIT (after reading the comments): If you want to delete all 0-length files in the directory, you can
use Directory.GetFiles to get a list of all the files in the directory,
use FileInfo.Length to get the size of the files, and then
use File.Delete to remove certain files.
In fact, the MSDN page on FileInfo.Length contains an example that outputs a list of files and their sizes in a given directory. You should be able to adapt this example to delete all files with 0 length.
In regards to you first question - you delete a 0 length file the same way you do any other file:
File.Delete(pathTo0LengthFile);
Your second question doesn't make sense. You can save your file in any path on the drive that the account the application runs under has write permissions to.
There are several system and special folders that you can get the path of use Environment.GetFolderPath - perhaps that's what you mean.

Categories