Access file in Resources C# - c#

I would like to import to registry a .reg file that exist in project resources.
The way to import a reg file uses the path to the reg file:
Process proc = new Process();
proc = Process.Start("regedit.exe", "/s " + "path\to\file.reg");
Is it possible to do so with a file from resources? how do I get its path?

If it is in the project folder. i-e. The folder in which the project is runnung. you can access it directly : Process.Start("regedit.exe", "/s " + "Filename.reg");
you can get the current path by using
string path =System.AppDomain.CurrentDomain.BaseDirectory; // this will give u the path for debug folder
or
string projectPath= Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())); //This will give u the project path.
you can use both and navigate arround to get the path to your desired folder. eg if you want to access a file in the Resource folder inside the project folder u can use projectPath+"\\Resource\\filename.reg"

If the file is embedded resource (and as such is not created on disk), it is best to read it like this and save it to a temporary file using:
var path = System.IO.Path.ChangeExtension(System.IO.Path.GetTempFileName(), "reg");
Process.Start(path);
It may not be necessary to change the extension if you don't start the file directly but use Process.Start("regedit", "/s " + path) like you described in your question. Keep in mind that the file path should be escaped so it's parsed properly as the command line argument, temporary file path, though, will not contain spaces, so it should be okay.

This is not tested code, but you get the steps I hope:
Process proc = new Process();
proc.StartInfo.FileName = "regedit.exe";
proc.StartInfo.Arguments = "/s";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.Start();
StreamWriter stdin = myProcess.StandardInput;
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "<regfile>";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
stdin.Write(reader.ReadToEnd());
}

Related

Code or command to use embedded resource in Visual Studio

Can somebody provide me a starting point or code to access an embedded resource using C#?
I have successfully embedded a couple of batch files, scripts and CAD drawings which I would like to run the batch and copy the scripts and CAD files to a location specified in the batch file.
I'm struggling to find how to specify what the item is and set the path within the EXE. The below code is what I thought would work, but it failed and the others I found online all related to XML files.
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "\\Batchfile.bat";
p.Start();
I honestly don't even know if I'm looking at the correct way to do this as this is my first time using either C# or Visual Studio.
Open Solution Explorer add files you want to embed. Right click on the files then click on Properties. In Properties window and change Build Action to Embedded Resource.
After that you should write the embedded resources to file in order to be able to run it.
using System;
using System.Reflection;
using System.IO;
using System.Diagnostics;
namespace YourProject
{
public class MyClass
{
// Other Code...
private void StartProcessWithFile()
{
var assembly = Assembly.GetExecutingAssembly();
//Getting names of all embedded resources
var allResourceNames = assembly.GetManifestResourceNames();
//Selecting first one.
var resourceName = allResourceNames[0];
var pathToFile = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) +
resourceName;
using (var stream = assembly.GetManifestResourceStream(resourceName))
using (var fileStream = File.Create(pathToFile))
{
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(fileStream);
}
var process = new Process();
process.StartInfo.FileName = pathToFile;
process.Start();
}
}
}

Text content in pdf is not converted using pdf2swf

I am running c# application in service mode. And i am using pdf2swf tool to convert odf to swf format. Images saved in pdf is converting. But if any test adding to pdf is not getting converted in service mode.
But when run as UI mode(Consoleapplication.exe) then everything is getting converted.
string inputFileName = this.Filename;
string outputFileName = inputFileName.Replace("pdf", "swf");
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0} -o {1}", inputFileName, outputFileName);
string executingDirPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "");
string dataDirectoryPath = Path.Combine(executingDirPath, "pdf2swf.exe");
ProcessStartInfo psi = new ProcessStartInfo(dataDirectoryPath, sb.ToString());
psi.UseShellExecute = false;
System.Diagnostics.Process pdf2swf = new System.Diagnostics.Process();
pdf2swf.StartInfo = psi;
pdf2swf.Start();
pdf2swf.WaitForExit();
pdf2swf.Close();
pdf2swf.Dispose();
Regards
Sangeetha
Direct using process to start pdf2swf.ext maybe had some privilege problems.I used another way to solve this problem,write a batch file,then running the batch file by process.
Batch file sample:
c:
cd C:\Program Files (x86)\SWFTools\
pdf2swf.exe -f -T 9 -t "%1" -o "%2"
Code in program:
Process p = new Process();
string path = basePath + "/plugin/ConvertToSwf.bat";//batch file path
ProcessStartInfo pi = new ProcessStartInfo(path, filePath + " " + swfPath);//passing the file path and converted file path to batch file
pi.UseShellExecute = false;
pi.RedirectStandardOutput = true;
p.StartInfo = pi;
p.Start();
p.WaitForExit();
I faced a similar problem recently. I solved the issue by adding a separate console application(Consoleapplication.exe) with administrative-rights that runs on my server without shell.
Also, try to upgrade to the newest version of pdf2swf.
FYI. I recently had this problem (thought it was fonts not being embedded but actually was missing all text in converted swf). What fixed it for me was to set:
pi.UseShellExecute = false;
AND set the working directory;
pi.WorkingDirectory = "C:\windows\temp"; // path where read & write is

Issue in File path

In my project there is a folder and in that folder there is text file. I want to read that text file
string FORM_Path = #"C:\Users\...\Desktop\FormData\Login.txt";
bool first = true;
string line;
try
{
using (StreamReader streamReader = File.OpenText(FORM_Path))
{
line = streamReader.ReadLine();
}
}
but I always get an error - file does not exist. how can i solve the problem in the path of text file.
Make sure your file's properties are set to copy the file to output directory. Then you can use the following line to get full path of your text file:
string FilePath = System.IO.Path.Combine(Application.StartupPath, "FormData\Login.txt");
You path is not in correct format. Use #".\FormData\Login.txt" instead of what you have
You are trying to give relative path instead of physical path. If you can use asp.net use Server.MapPath
string FORM_Path = Server.MapPath("~/FormData/Login.txt");
If the text file is in execution folder then you can use AppDomain.BaseDirectory
string FORM_Path = AppDomain.CurrentDomain.BaseDirectory + "FormData\\Login.txt";
If it is not possible to use some base path then you can give complete path.
Avoid using relative paths. Instead consider using the methods in the Path class.
Path.Combine
Path.GetDirectoryName
Step 1: get absolute path of the executable
var path = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
Step 2: get the working dir
var dir = Path.GetDirectoryName(path);
Step 3: build the new path
var filePath = Path.Combine(dir , #"FormData\Login.txt");

Copy files from one path to another path in c#

If
frompath = "c:\\progfiles\\mobileapp\\es-gl\\a.dll"
and
topath = "c:\\progfiles\\mobileapp\\es-gl\\a.dll"
I want to copy file from frompath to topath.
If topath does not exist, then the directories and sub directories must get created and the file a.dll must copy from frompath to topath. I am using c# .net Compact Framework.
I think you are after the System.IO namespace. Using File.Copy can provide the solution.
And Directory.Exists / create can make the directory is not existing.
var fileName = "tmp.txt";
var from = #"c:\temp\" + fileName;
var to = #"c:\temp\1\";
if (!Directory.Exists(to))
Directory.CreateDirectory(to);
File.Copy(from, to + fileName);
You can go for FileInfo aswell. (Also in the System.IO namespace)
var file = new FileInfo(#"c:\temp\tmp.txt");
var to = #"c:\temp\1\";
if (!Directory.Exists(to))
Directory.CreateDirectory(to);
file.CopyTo(to + file.Name);

Auto FTP from a Directory

I want to monitor a directory and FTP any files that are place there to an FTP location. does anyone know how to do this in c#?
Thanks
EDIT: Anyone know of a good client that can monitor a directory and FTP and files placed in it?
I combination of the System.IO.FileSystemWatcher and System.Net.FtpWebRequest/FtpWebResponse classes.
We need more information to be more specific.
When used in conjunction with the FileSystemWatcher, this code is a quick and dirty way to upload a file to a server.
public static void Upload(string ftpServer, string directory, string file)
{
//ftp command will be sketchy without this
Environment.CurrentDirectory = directory;
//create a batch file for the ftp command
string commands = "\n\nput " + file + "\nquit\n";
StreamWriter sw = new StreamWriter("f.cmd");
sw.WriteLine(commands);
sw.Close();
//start the ftp command with the generated script file
ProcessStartInfo psi = new ProcessStartInfo("ftp");
psi.Arguments = "-s:f.cmd " + ftpServer;
Process p = new Process();
p.StartInfo = psi;
p.Start();
p.WaitForExit();
File.Delete(file);
File.Delete("f.cmd");
}

Categories

Resources