I'm using System.Diagnostics.Process.Start("my.exe"); to call an exe
Now that I can call my .exe, I want to bind/merge it into my c# application so that when I build my application, I can get the exe built inside the projectName\Debug\builtProgram.exe or any other way to finally get a single exe file with my desired exe file inside it.
For example, consider I create a program A and I want it to encase it inside another program B which contains only one button 'Launch Program A'. And let's say program B is portable - with a single exe file.
Question is - How to create program B?
You can include the .exe as an embedded resource in your .NET assembly, and then dump it to disk to a temporary file on startup:
var thisAssembly = Assembly.GetExecutingAssembly();
var executableFileName = Path.GetTempFileName();
using(resourceStream = thisAssembly.GetManifestResourceStream("name.of.resource.exe"))
using(fileStream = File.Create(executableFileName))
{
resourceStream.CopyTo(fileStream);
}
Then you call it just like you would normally.
Process.Start(executableFileName);
Since it's hard for me to extract embedded resource.
Here's my answer:
public static void getbytez(string file, string outp)
{
byte[] buffer = File.ReadAllBytes(file);
string base64Encoded = Convert.ToBase64String(buffer);
File.WriteAllText(outp+ ".txt", base64Encoded);
//copy the base64encoded text.
//Code by CursedGmod. credit me please :D
}
public static void extract2idk(string txtfile, string outp, string exten)
{
byte[] gu = Convert.FromBase64String(txtfile);
// use it like this: byte[] gu = Convert.FromBase64String(your base64 converted text that you copied from the txt file);
// or use File.ReadAllText if you're making a stub builder.
File.WriteAllBytes(outp + exten, gu);
Process.Start(Environment.ExpandEnvironmentVariables("%TEMP%") + Path.GetFileName(txtfile));
}
Related
I have an image file day.jpg in Resources folder and I want to access it in the code as string path not as byte[] img
Here's what I have tried.
string dayWallpaper = Assembly.GetExecutingAssembly().Location + #"..\..\Resources\day.jpg";
// Didn't found it
string dayWallpaper = Resource.day;
// Outputs byte[] and gives me an error
Then I tried to convert the byte[] to String didn't work as well
static byte[] SliceMe(byte[]? source, int pos)
{
byte[]? destfoo = new byte[source.Length - pos];
Array.Copy(source, pos, destfoo, 0, destfoo.Length);
return destfoo;
}
static string ByteToPath(path)
{
String file = Encoding.Unicode.GetString(SliceMe(path, 24)).TrimEnd("\0".ToCharArray());
return file
}
Outputs black screen
Later I search for the file
if (File.Exists(dayWallpaper))
{
do stuff
}
else
{
Console.WriteLine("File does not exists");
}
And gives me the else statement.
In the answer you posted to your question, the fact that your relative path works is an "accident" that would fail on any other device deploying your app because without the existence of the source code project the path doesn't exist. One good option is to mark the day.jpg file as Copy to Output Directory at which point most installer bundlers will pick it up and deploy it in your setup.exe, msi etc. If you are specifically using the Visual Studio IDE, you would do it like this:
Now, at runtime, to acquire the path to the copied file:
var srce = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "day.jpg");
However, there is more work to be done, because you state that you "want to store the image in a folder in the executable and the user could add more images later on." The present location of the file is not suitable for that purpose, so I would recommend the additional step of creating an AppData entry for the user to store their created content.
// Obtain a folder that "the user could add to later on".
var appData =
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
typeof(Program).Assembly.GetName().Name
);
Directory.CreateDirectory(appData);
Since you mention wanting to store the day.jpg image in that folder, go ahead and copy it to the AppData location (if not already there from a previous run of your app).
var dest = Path.Combine(appData, "day.jpg");
// Copy the image (if it's not there already) into folder that the user can add to.
if (!File.Exists(dest))
{
File.Copy(
sourceFileName: srce,
destFileName: dest
);
}
Alternatively, you could set the BuildAction to EmbeddedResource and manipulate the file as a byte stream and achieve the same end result.
I managed to do it this way
string resourcePath = Path.GetFullPath(Assembly.GetExecutingAssembly().Location + #"\..\..\..\..\Resources");
string dayWallpaper = resourcePath + #"\day.jpg";
I am developing a windows 8 app using Microsoft visual studio 2013. I needed to store the user entered data in a text file. I have wrote the following code segment to create the file and its working. But the text file is created in C:\Users...... I want to create the text file in a given folder. How can I modify my code to create the file in a folder where I specify.
StorageFile sampleFile;
const string fileName = "Sample.txt";
This is how you can create a file in C temp folder
String folderPath = #"C:/temp";
FileStream fs = new FileStream(folderPath + "\\Samplee.txt",FileMode.OpenOrCreate, FileAccess.Write);
As told before, Universal apps are sandboxed which means you can't write a file in an arbitrary folder.
You should take a look at the File access sample on how to do it.
Also, you should take a look at the ApplicationData which gives you a lot of choices for saving user entered data. Is it temporary, do you want it to be synced, is it a setting? There sure is a property that suits your needs.
edit: from http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.applicationdata.localfolder.aspx this is what you should do
var applicationData = Windows.Storage.ApplicationData.current;
var localFolder = applicationData.localFolder;
// Write data to a file
function writeTimestamp() {
localFolder.createFileAsync("dataFile.txt", Windows.Storage.CreationCollisionOption.replaceExisting)
.then(function (sampleFile) {
var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
var timestamp = formatter.format(new Date());
return Windows.Storage.FileIO.writeTextAsync(sampleFile, timestamp);
}).done(function () {
});
}
You need to set the directory where you want to save the file.
Try this
string dirctory = #"D:\Folder Name"; //This is the location where you want to save the file
if (!Directory.Exists(dirctory))
{
Directory.CreateDirectory(dirctory);
}
File.WriteAllText(Path.Combine(dirctory, "Sample.txt"), "Text you want to Insert");
My current project uses a direct file path of this excel document to read information off of the excel file. I need to get my project ready for release so I cannot have the project hard code a file path in the form of a string.
I want to embed the Excel File in my resource, which I have done, but know how can I get the file path from Resource, and send a file path to the class which reads the Excel file. The class must be feed a filepath so I was thinking of making a copy of this Excel file, and in the Temp folder then referenceing the file path for the class to read the Excel file.
FileName = #"D:\SomeFolder\ExcelFile.xlsx"; //This is the old code, hard coded
//I need code that is going to make a copy of this file from the Resources and save it somewhere in a temp folder, but then give me
the File path in the form of a string.
string FileName;
// I need the file name to have the directory of this excel that is in the Resource folder
//Call Class to Create XML File and store Data from BIN File Locally on Program
ReadExcel_CreateXML = new ExcelRecorder(FileName);
Something else to think about is that you are probably reading the current files using a FileStream and either a BinaryReader or StreamReader. If that's the case, the consumer of the file could be written to accept an arbitrary Stream instead and then you can create a MemoryStream to pass to the consuming class:
// The resource will be a byte array, I'm just creating a
// byte array manually for example purposes.
var fileData = System.Text.Encoding.UTF8.GetBytes("Hello\nWorld!");
using (var memoryStream = new MemoryStream(fileData))
using (var streamReader = new StreamReader(memoryStream))
{
// Do whatever you need with the file's contents
Console.WriteLine(streamReader.ReadLine());
Console.WriteLine(streamReader.ReadLine());
}
This approach means you won't be cluttering up the client computer with temporary files that you'll need to clean up. It also means your consuming class will become more flexible if you ever need to process data over any other type of Stream.
I'm not sure if this the best solution, but it will work:
1st get the byte[] array of the file in your resources:
byte[] fileByteArray = global::YourProjectNameSpace.Properties.Resources.ExcelFileName
2nd Export the file to a temporary location using this function:
(I got from here: Write bytes to file)
public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
{
try
{
// Open file for reading
System.IO.FileStream _FileStream =
new System.IO.FileStream(_FileName, System.IO.FileMode.Create,
System.IO.FileAccess.Write);
// Writes a block of bytes to this stream using data from
// a byte array.
_FileStream.Write(_ByteArray, 0, _ByteArray.Length);
// close file stream
_FileStream.Close();
return true;
}
catch (Exception _Exception)
{
// Error
Console.WriteLine("Exception caught in process: {0}",
_Exception.ToString());
}
// error occured, return false
return false;
}
And last access that temporary file like you normally would
Use:
Just create a button in a form and put this code in the button's click event
private void button1_Click(object sender, EventArgs e)
{
byte[] fileByteArray = global::YourProjectNameSpace.Properties.Resources.ExcelFileName;
if (ByteArrayToFile(#"C:\Temp\file.xlsx", fileByteArray))
{
//File was saved properly
}
else
{
//There was an error saving the file
}
}
Hope it works
I am trying to create a torrent for the files in my desktop using monotorrent i have tried like the below code
i am able to get the byte code i am not able to save it as torrent it shows access denied
enter code here string path = "C:/Users/snovaspace12/Desktop/monotorrent-0.90/files";
string savepath = "D:/results";
TorrentCreator nnnn = new TorrentCreator();
nnnn.CreateTorrent(path, savepath);
public void CreateTorrent(string path, string savePath)
{
// The class used for creating the torrent
TorrentCreator c = new TorrentCreator();
// Add one tier which contains two trackers
//RawTrackerTier tier = new RawTrackerTier();
//tier.Add("http://localhost/announce");
//c.Announces.Add(tier);
c.Comment = "This is the comment";
c.CreatedBy = "Doug using " + VersionInfo.ClientVersion;
c.Publisher = "www.aaronsen.com";
// Set the torrent as private so it will not use DHT or peer exchange
// Generally you will not want to set this.
c.Private = true;
// Every time a piece has been hashed, this event will fire. It is an
// asynchronous event, so you have to handle threading yourself.
c.Hashed += delegate(object o, TorrentCreatorEventArgs e)
{
Console.WriteLine("Current File is {0}% hashed", e.FileCompletion);
Console.WriteLine("Overall {0}% hashed", e.OverallCompletion);
Console.WriteLine("Total data to hash: {0}", e.OverallSize);
};
// ITorrentFileSource can be implemented to provide the TorrentCreator
// with a list of files which will be added to the torrent metadata.
// The default implementation takes a path to a single file or a path
// to a directory. If the path is a directory, all files will be
// recursively added
ITorrentFileSource fileSource = new TorrentFileSource(path);
// Create the torrent file and save it directly to the specified path
// Different overloads of 'Create' can be used to save the data to a Stream
// or just return it as a BEncodedDictionary (its native format) so it can be
// processed in memory
c.Create(fileSource, savePath);
}
public void Create(ITorrentFileSource fileSource, string savePath)
{
Check.SavePath(savePath);
var file = Create(fileSource);//getting the fbyte code
File.WriteAllBytes( savePath, Create(fileSource).Encode()); //getting exception here
}
when i checked the byte code is returning properly to the file
it shows access is denied
You’ve probably solved this already but I just encountered the same issue. The solution, at least in my case, was pretty simple.
The problem originated with the savePath parameter in c.Create(fileSource, savePath);
I assumed savePath was a directory where the torrent would be saved. It should be a file path instead. For example savePath = “C:\pathtomytorrents\content.torrent”
Hopefully that works for you!
How do I embed an external executable inside my C# Windows Forms application?
Edit: I need to embed it because it's an external free console application (made in C++) from which I read the output values to use in my program. It would be nice and more professional to have it embedded.
Second reason is a requirement to embed a Flash projector file inside a .NET application.
Simplest way, leading on from what Will said:
Add the .exe using Resources.resx
Code this:
string path = Path.Combine(Path.GetTempPath(), "tempfile.exe");
File.WriteAllBytes(path, MyNamespace.Properties.Resources.MyExecutable);
Process.Start(path);
Here is some sample code that would roughly accomplish this, minus error checking of any sort. Also, please make sure that the license of the program to be embedded allows this sort of use.
// extracts [resource] into the the file specified by [path]
void ExtractResource( string resource, string path )
{
Stream stream = GetType().Assembly.GetManifestResourceStream( resource );
byte[] bytes = new byte[(int)stream.Length];
stream.Read( bytes, 0, bytes.Length );
File.WriteAllBytes( path, bytes );
}
string exePath = "c:\temp\embedded.exe";
ExtractResource( "myProj.embedded.exe", exePath );
// run the exe...
File.Delete( exePath );
The only tricky part is getting the right value for the first argument to ExtractResource. It should have the form "namespace.name", where namespace is the default namespace for your project (find this under Project | Properties | Application | Default namespace). The second part is the name of the file, which you'll need to include in your project (make sure to set the build option to "Embedded Resource"). If you put the file under a directory, e.g. Resources, then that name becomes part of the resource name (e.g. "myProj.Resources.Embedded.exe"). If you're having trouble, try opening your compiled binary in Reflector and look in the Resources folder. The names listed here are the names that you would pass to GetManifestResourceStream.
Just add it to your project and set the build option to "Embedded Resource"
This is probably the simplest:
byte[] exeBytes = Properties.Resources.myApp;
string exeToRun = Path.Combine(Path.GetTempPath(), "myApp.exe");
using (FileStream exeFile = new FileStream(exeToRun, FileMode.CreateNew))
exeFile.Write(exeBytes, 0, exeBytes.Length);
Process.Start(exeToRun);
Is the executable a managed assembly? If so you can use ILMerge to merge that assembly with yours.
Here's my version:
Add the file to the project as an existing item, change the properties on the file to "Embedded resource"
To dynamically extract the file to a given location: (this example doesn't test location for write permissions etc)
/// <summary>
/// Extract Embedded resource files to a given path
/// </summary>
/// <param name="embeddedFileName">Name of the embedded resource file</param>
/// <param name="destinationPath">Path and file to export resource to</param>
public static void extractResource(String embeddedFileName, String destinationPath)
{
Assembly currentAssembly = Assembly.GetExecutingAssembly();
string[] arrResources = currentAssembly.GetManifestResourceNames();
foreach (string resourceName in arrResources)
if (resourceName.ToUpper().EndsWith(embeddedFileName.ToUpper()))
{
Stream resourceToSave = currentAssembly.GetManifestResourceStream(resourceName);
var output = File.OpenWrite(destinationPath);
resourceToSave.CopyTo(output);
resourceToSave.Close();
}
}
Add File to VS Project
Mark as "Embedded Resource" -> File properties
Use name to resolve: [Assembly Name].[Name of embedded resource] like "MyFunkyNTServcice.SelfDelete.bat"
Your code has resource bug (file handle not freed!), please correct to:
public static void extractResource(String embeddedFileName, String destinationPath)
{
var currentAssembly = Assembly.GetExecutingAssembly();
var arrResources = currentAssembly.GetManifestResourceNames();
foreach (var resourceName in arrResources)
{
if (resourceName.ToUpper().EndsWith(embeddedFileName.ToUpper()))
{
using (var resourceToSave = currentAssembly.GetManifestResourceStream(resourceName))
{
using (var output = File.OpenWrite(destinationPath))
resourceToSave.CopyTo(output);
resourceToSave.Close();
}
}
}
}
Extract something as string, if needed:
public static string ExtractResourceAsString(String embeddedFileName)
{
var currentAssembly = Assembly.GetExecutingAssembly();
var arrResources = currentAssembly.GetManifestResourceNames();
foreach (var resourceName in arrResources)
{
if (resourceName.ToUpper().EndsWith(embeddedFileName.ToUpper()))
{
using (var resourceToSave = currentAssembly.GetManifestResourceStream(resourceName))
{
using (var output = new MemoryStream())
{
resourceToSave.CopyTo(output);
return Encoding.ASCII.GetString(output.ToArray());
}
}
}
}
return string.Empty;
}