c# opening an embedded file (.doc, .pdf, .exe etc.) - c#

I am new to C# and I have normally built windows forms using VB and was able to use one code to open any embedded file I added to my "Resources". As far as C# I have looked online for hours and have yet to find anything that worked. Please assist in any way that you can.
I have a Windows Form that will have a single button that will be assigned to open a particular file I have added to the "Resources" folder. Usually I would use the following code to have a Button_Click to load an exe, doc or pdfile. I am looking for something similar for C#.
VB Code:
IO.File.WriteAllBytes(My.Computer.FileSystem.SpecialDirectories.Temp & "\IEResetConfigure.exe", My.Resources.IEResetConfigure)
Process.Start(My.Computer.FileSystem.SpecialDirectories.Temp & "\IEResetConfigure.exe")

Simply write your resource file to temporary directory and run the file
using System;
using System.IO;
using System.Diagnostics;
// ...
byte[] resourceFile = Properties.Resources.Newspaper_PC_13_12_2013;
string destination = Path.Combine(Path.GetTempPath(), "Newspaper_PC_13_12_2013.pdf");
System.IO.File.WriteAllBytes(destination, resourceFile);
Process.Start(destination);

Example of my comment
using System;
using System.IO;
using System.Diagnostics;
using System.Threading.Tasks;
// ...
static void Main(string[] args)
{
byte[] resourceFile = Properties.Resources.Newspaper_PC_13_12_2013;
string destination = Path.Combine(Path.GetTempPath(), "Newspaper_PC_13_12_2013.pdf");
File.WriteAllBytes(destination, resourceFile);
Process.Start(destination);
AutoDelete(2000, destination);
Console.Write("Press any key to quit . . . ");
Console.ReadKey(true);
}
static async void AutoDelete(int milliseconds, string destination)
{
while (File.Exists(destination))
{
await Task.Delay(milliseconds);
try
{
File.Delete(destination);
}
catch
{
continue;
}
}
}

For anyone still looking, Here is a way of opening an "embedded" file. I'd love for someone to correct me below on a better way.
The first part is to make sure your file is added to your project in the bin\debug folder.
I then used this code to call it
private void button1_Click(object sender, EventArgs e)
{
//Place file in .\bin\Debug folder of project
string filename = "YourFileName.pdf";
System.Diagnostics.Process.Start(filename);
For full Disclosure this whole part has been stolen from
(Opening a .pdf file in windows form through a button click)
I did however run into an issue where after the first build that didn't work for me. So when I created the setup project I added the "Project Output" and then added in my pdf via "add file" to the application folder.
That has continued to work flawlessly for me since.
This is my first post on Stack Overflow, so please let me know if I misunderstood any rules or could improve. Thank you and I hope this helped!

Related

How do I create this directory using this function? I keep getting an access denied error.(C#)

First, let me begin by saying I know this appears to be a commonly asked question, but trust me, I've searched extensively and I couldn't find the answer to my question specifically. IF you do happen to know where this specific question was asked, by all means, mark it as a duplicate and reference me there, and accept my apologies for not finding it.
Now, I have a simple if function in my code:
if (!Directory.Exists(FileDirectory))
{
Directory.CreateDirectory(FileDirectory);
}
However, upon running this if Function, I get this error code:
System.UnauthorizedAccessException: 'Access to the path 'C:\Program Files\LockingProgram\Password.txt;' is denied.'
Now, obviously the problem is that the access is denied. How would I gain access?
I have tried simply writing the file instantly, however then it won't find the path
File.WriteAllText(FileDirectory, Password);
throws this error:
System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Program Files\LockingProgram\Password.txt;'
The FileDirectory string is:
string FileDirectory = "C:\\Program Files\\LockingProgram\\Password.txt;";
Currently, what the program is trying to do is get a password from the user when they click a button, and then saves that password to a txt file located at the file directory for future reference. When they open the program, it checks if the file exists. If it exists, it sets the password to that file, and if it doesn't it forces the user to enter a string into a text box and from there, I am trying to save it. However, that's where I'm having the problem.
Any help would be greatly appreciated!
Edit: I now understand it's generally a bad idea to save it to Program Files, and you should use AppData instead. I'll try that and update you if it works that time.
Edit 2: It now works. I changed the file directory to:
string FileDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "LockingApp";
And I added a new variable:
string FileName = "Password.txt";
And I modified where the directory is created to:
if (!Directory.Exists(FileDirectory))
{
Directory.CreateDirectory(FileDirectory);
}
File.WriteAllText(Path.Combine(FileDirectory, FileName), Password);
Thanks for your help guys! Hopefully I formatted this question well.
C:\\Program Files\\LockingProgram\\Password.txt;
is not a directory, use
FileDirectory = #"C:\Program Files\LockingProgram";
Directory.CreateDirectory(FileDirectory);
Also there is a probably a good chance you will need to run your program at an elevated privilege or with the appropriate permissions, i.e as an administrator
However there are better places to store data
Where Should I Store my Data and Configuration Files if I Target Multiple OS Versions?
ie AppData, for example
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
You can use Isolated Storage for saving files (Seems the easiest and least tasking to use).
Check this code sample below
using System;
using System.IO;
using System.IO.IsolatedStorage;
public class CreatingFilesDirectories
{
public static void Main()
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null))
{
isoStore.CreateDirectory("TopLevelDirectory");
isoStore.CreateDirectory("TopLevelDirectory/SecondLevel");
isoStore.CreateDirectory("AnotherTopLevelDirectory/InsideDirectory");
Console.WriteLine("Created directories.");
isoStore.CreateFile("InTheRoot.txt");
Console.WriteLine("Created a new file in the root.");
isoStore.CreateFile("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt");
Console.WriteLine("Created a new file in the InsideDirectory.");
}
}
}

Starting a .exe file but won't work?

I wanted to start a .exe file in a different folder but I wanted other people to also use it and I've been trying many things but it just keeps opening the file that the program that I'm creating is in. (I'm new to c#).
My ex of ^: \Desktop\VSCheatDetector\CheatDetector.exe(the program) and another regular file named viper_screenshare_tool and it has CheatDetector.exe (which I want to open when I click a certain button)
Code:
private void cheat_smasher_click(object sender, EventArgs e)
{
string dir = AppDomain.CurrentDomain.BaseDirectory;
Process.Start(dir, "vipers_screenshare_tool\\CheatDetector.exe");
}
You don't want to use AppDomain.CurrentDomain.BaseDirectory; - I'd suggest using App.config or something like that instead.

How to append a text file on SFTP server using SharpSSH or SSH.NET library

I use Tamir.SharpSSH library to make my SFTP operations. I can upload file from client, delete or list files located in an SFTP server directory.
But I cannot find how to append a text file. I don't want to overwrite or delete the existing and upload a new one. I have a log file on that SFTP server. I have to add new lines to that file from client side.
I just searched the internet and looked different functions in the code but tried nothing to execute because I could not find anything till now.
Thanks in advance
EDIT
I decided to use Renci.SshNet library because of #Martin Prikryl's advise. I tried the above operations with that library also and I saw it works good. Also appending text to a text file is very simple with that library. I'm sharing a small example about that here:
using System
using Renci.SshNet;
namespace SFTPConnectSample
{
class Program
{
static void Main(string[] args)
{
AppendText(#"/targetFolder/targetFile.txt");
}
private static void AppendText(string targetFilePath)
{
int portNumber = 22;
using (SftpClient sftp = new SftpClient("myHostName", portNumber, "sftpUser", "sftpPassword"))
{
sftp.ConnectionInfo.Timeout = new TimeSpan(0, 0, 30);
sftp.Connect();
sftp.AppendAllText(targetFilePath, "\r\nThis is a new line for target text file.");
}
}
}
}
First, do not use SharpSSH. It's an abandoned project, not updated for years.
You can use SSH.NET library instead.
Its SftpClient class has couple of methods you can use:
public StreamWriter AppendText(string path)
public void AppendAllText(string path, string contents)
public void AppendAllLines(string path, IEnumerable<string> contents)
If you must use SharpSSH for some reason, use:
SftpChannel.get(fromFilePath, toFilePath, monitor, ChannelSftp.APPEND);

How to display chm file in c# winforms application

I have added .chm file to my application root. when i fetch the file using below code it is referencing the path to bin/release/somehting.chm
System.Windows.Forms.Help.ShowHelp(this, Application.StartupPath+"\\"+"somehting.chm");
i want to get the path relative to installation location of application. please help.
the chm file added to the root directory is not loading after deploying the application. its not even loading while debugging in visual studio and not giving any error.
As I can see the first code snippet from your question calling Help.ShowHelp isn't so bad. Sometimes I'm using the related code below. Many solutions are possible ...
Please note, typos e.g. somehting.chm are disturbing in code snippets.
private const string sHTMLHelpFileName = "CHM-example.chm";
...
private void button1_Click(object sender, EventArgs e) {
System.Windows.Forms.Help.ShowHelp(this, Application.StartupPath + #"\" + sHTMLHelpFileName);
}
So, please open Visual Studio - Solution Explorer and check the properties of your CHM file. Go to the dropdown box shown in the snapshot below and set "Always copy" (here only German). Start your project in Debug mode and check your bin/debug output folder. Do the same for Release mode and output folder. The CHM should reside there and I hope your CHM call works.
You need :
String exeDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
So :
String HelpFilepath = "file://" + Path.Combine(exeDirectory , "somehting.chm");
Help.ShowHelp(this, path);
Answer from similar topic is:
// get full path to your startup EXE
string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
// get directory of your EXE file
string exeDir = Path.GetDirectoryName(exeFile);
// and open Help
System.Windows.Forms.Help.ShowHelp(this, exeDir+"\\"+"somehting.chm");

How to play WAV audio file from Resources?

How can I play a WAV audio file in from my project's Resources? My project is a Windows Forms application in C#.
Because mySoundFile is a Stream, you can take advantage of SoundPlayer's overloaded constructor, which accepts a Stream object:
System.IO.Stream str = Properties.Resources.mySoundFile;
System.Media.SoundPlayer snd = new System.Media.SoundPlayer(str);
snd.Play();
SoundPlayer Class Documentation (MSDN)
a) OK, first add audio file (.wav) into project resource.
Open "Solution Explorer" from menu toolbar ("VIEW") or simply press Ctrl+Alt+L.
Click on drop-down list of "Properties".
Then select "Resource.resx" and press enter.
Now select "Audio" from the combobox list.
Then click on "Add Resource", choose audio files (.wav) and click "Open".
Select audio file(s) and change "Persistence" properties to "Embedded in .resx".
b) Now, just write this code to play the audio.
In this code I'm playing audio on form load event.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media; // at first you've to import this package to access SoundPlayer
namespace WindowsFormsApplication1
{
public partial class login : Form
{
public login()
{
InitializeComponent();
}
private void login_Load(object sender, EventArgs e)
{
playaudio(); // calling the function
}
private void playaudio() // defining the function
{
SoundPlayer audio = new SoundPlayer(WindowsFormsApplication1.Properties.Resources.Connect); // here WindowsFormsApplication1 is the namespace and Connect is the audio file name
audio.Play();
}
}
}
That's it.
All done, now run the project (press f5) and enjoy your sound.
All the best. :)
Stream str = Properties.Resources.mySoundFile;
RecordPlayer rp = new RecordPlayer();
rp.Open(new WaveReader(str));
rp.Play();
From How to play WAV audio file from resources in C#.
You need to be cautious about the garbage collector freeing up memory used by your sound while the sound is still playing. While it rarely happens, when it does, you will just be playing some random memory. There is a solution to this, complete with source code for achieving what you want here: http://msdn.microsoft.com/en-us/library/dd743680(VS.85).aspx
Scroll to the very bottom, in the "Community Content" section.
Theses two lines can do it:
SoundPlayer sound = new SoundPlayer(Properties.Resources.solo);
sound.Play();
There are two ways to do so as far as I know, list below:
Use file path
First put the file in the root folder of the project, then no matter you run the program under Debug or Release mode, the file can both be accessed for sure. Then use the class SoundPlayer to paly it.
But in this way, if you want to release the project to users, you need to copy the sound files with its folder hierarchies except hierarchies the folder "Release" under the "bin" directory.
var basePath = System.AppDomain.CurrentDomain.BaseDirectory;
SoundPlayer player = new SoundPlayer();
player.SoundLocation = Path.Combine(basePath, #"./../../Reminder.wav");
player.Load();
player.Play();
Use resource
Follow below animate, add "Exsiting file" to the project.
SoundPlayer player = new SoundPlayer(Properties.Resources.Reminder);
player.Play();
The strength of this way is:
Only the folder "Release" under the "bin" directory need to be copy when run the program.
When you have to add sounds into your project, you will do so by playing .wav file(s). Then you have to add the .wav file(s) like this.
using System.Media; //write this at the top of the code
SoundPlayer my_wave_file = new SoundPlayer("F:/SOund wave file/airplanefly.wav");
my_wave_file.PlaySync(); // PlaySync means that once sound start then no other activity if form will occur untill sound goes to finish
Remember that you have to write the path of the file with forward slashes (/) format, don't use back slashes (\) when giving a path to the file, else you will get an error.
Also note, if you want other things to happen while the sound is playing, you can change my_wave_file.PlaySync(); with my_wave_file.PlayAsync();.

Categories

Resources