How to execute a file within a subdirectory - c#

So I have a small setup file that needs to install a few run-time files. The files are located within sub directories of the root of the drive. The drive letter will be different on every customers machine, so I was trying this and several other methods to no avail.
// File is being ran from D:\ "eg: D:\setup.exe"
// All my runtimes are in the Tools\Runtime direcorties
string path = Directory.GetCurrentDirectory();
string ext = "/q /norestart";
string location = "\\Tools\\Runtimes\\Net\\";
string step1 = "dotnetfx35.exe";
var process = Process.Start(path + location + step1 + ext);
process.WaitForExit();
As you pros and more experienced programmers know, for some reason... It doesn't work
I keep getting file not found.

Related

Using an exe file for IExpress

I'm making an installer using IExpress to unpack the files, create a folder and move the files to the folder.
However, when choosing which program to run upon installation I can only get it to work using a batch-file:
#ECHO OFF
MD C:\PlugInFolder
MOVE /Y "%USERPROFILE%\AppData\Local\Temp\IXP000.TMP\*.png" C:\PlugInFolder
MOVE /Y "%USERPROFILE%\AppData\Local\Temp\IXP000.TMP\PlugIn.dll" C:\PlugInFolder
MOVE /Y "%USERPROFILE%\AppData\Local\Temp\IXP000.TMP\PlugIn2021.addin" C:\ProgramData\Autodesk\Revit\Addins\2021
MOVE /Y "%USERPROFILE%\AppData\Local\Temp\IXP000.TMP\PlugIn2022.addin" C:\ProgramData\Autodesk\Revit\Addins\2022
Is it possible to run an exe file instead? I've tried the following C#-code (for one of the files only) but it only creates the folder and doesn't move the files:
// Creating paths
string path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string folderName = "PlugInFolder";
string pathString = Path.Combine(path, folderName) + "\\PlugIn.dll";
string tempName = Path.GetTempPath() + "IXP000.TMP\\";
string fileName = "PlugIn.dll";
string filePath = tempName + fileName;
// Creating new directory
Directory.CreateDirectory(pathString);
// Moving files from temp folder
File.Move(filePath, pathString);
There are a few typos in your code. Here's what could work, correctly using Path.Combine which is a powerful command:
// Creating paths
string source = Path.Combine(Path.GetTempPath(), "IXP000.TMP");
string dest1 = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string dest2 = "PlugInFolder";
string dest = Path.Combine(dest1, dest2);
// Creating new directory
// Directory.CreateDirectory(dest);
// Don't create the directory, because we will use Directory.Move
// and it would raise an exception "Directory already exists"
// Moving files from temp folder to destination
// File.Move is meant to move one file at a time.
// For an entire directory, use Directory.Move which can also be used for renaming the directory.
Directory.Move(source, dest);
And, by the way, is it a choice to put an application in the user profile dir? Otherwise, you may use:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
which would be C:\Users\yourName\AppData\Roaming for example in Windows 11.

C# - Access to Path is Denied, unable to access files

I'm working on a project that a series of images that are deposited in one area of memory (say from a memory stick or download), and distributes them out to their respective folders based on the name of the image - which should correspond with the names of the files in their respective folder.
I have the first few functions of the code written to make this happen and decided to test it by altering the code so that it would carry out the process on a collection of the files in the My Pictures folder.
What should have happened is that each file in the folder was copied to a folder in AppData called 'New Images', and added into the appropriate sub-directory or create the subdirectory if necessary.
This threw up an error stating that access to C:\Users\mark although it did not explain why or what to do about it.
I thought this might be a problem with accessing the My Pictures folder so I copied the images into a folder called 'Test Images' inside the AppData folder (so the program would now be just transferring files between two folders in AppData). The same error occurred and I don't really know what to do next, I have written and read from files in AppData many times before and never encountered this problem. I have also read various entries related to this on this forum but don't seem to be able to get a definitive answer in terms of what to do next!
The code that causes the exception can be seen below:
//main folder (Contains sub-folders for each patient)
string rootDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\New Images";
//variables for sub-directories cannot be given at this point as they are created using a part of the image name
string subDirectory;
//string subDirectory = Path.Combine(rootDirectory, imageName.Split('_')[0]);
string imageName;
//string imageName = Path.GetFileName(image)
string shortcutDirectory;
//string shortcutDirectory = My Documents + Subfolder name + file name
//list to hold all strings as bitmap image
List<Bitmap> images = new List<Bitmap>();
public void createDirectory()
{
//create filing construct for all files passed in from machines
//if main folder does not exist in AppData
if (!Directory.Exists(rootDirectory))
{
//create it
Directory.CreateDirectory(rootDirectory);
}
}
public void saveLatestImages()
{
//specific path for My Pictures only
string testImagesPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Test Images";
//if there is a Pictures folder
if (Directory.Exists(testImagesPath))
{
//get number of files in folder
int fileCount = Directory.GetFiles(testImagesPath).Count();
//more than one file in folder
if (fileCount > 0)
{
//create data structures to store file info
//filePaths holds path of each file represented as a string
string[] filePaths = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Test Images");
//for each file in Pictures...
for (int index = 0; index < fileCount; ++index)
{
//get name of image at current index
imageName = filePaths[index];
//separate the part relating to the patient name (everything before (DD/MM/YYYY))
string subSpecifier = imageName.Split('_')[0];
//add to root directory to form subfolder name
subDirectory = Path.Combine(rootDirectory, subSpecifier);
//subdirectory name formulated, check for pre-existing
//subfolder does not exist
if(!Directory.Exists(subDirectory))
{
//create it
Directory.CreateDirectory(subDirectory); //ERROR OCCURS
}
//otherwise, file will be added to existing directory
//take everything from end and folder\file division to get unique filename
string fileName = imageName.Split('\\').Last();
//add this to the existing subDirectory
fileName = Path.Combine(subDirectory, fileName);
//copy the image into the subfolder using this unique filename
File.Copy(imageName, fileName);
//add full filename to list of bitmap images
images.Add(new Bitmap(fileName));
//update the shortcut to the file in the image storage shortcut folder
shortcutDirectory = getShortcut(subSpecifier, fileName);
//delete image at original path (clear folder so images not copied on next load up)
//File.Delete(imageName);
}
}
}
}
Any help in where to look next would be greatly appreciated!
Thanks
Mark
Is this an ASP.net web application ? In that case can you try providing write permission to the IIS_IUSRS account.
The trick to solve this is ASP.net Impersonation .
Do not give full rights and run your app as an admin. Users will then have admin rights and I am sure you would want to avoid that.
For time being give full rights to everyone to your folder and try running your application as an administrator.
If that works then your can change permissions on your folder accordingly. Also make sure that your folder isn't readonly.

how to create a new uri which needs to contain a string

I'm using a web browser and the uri that the web browser displays is constantly changing.
The exact location of the uri is not known as users will install the program containing the files to their Program Files folder.
If I use
directoryString += Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
It will return C://Program Files (x86) as I want it to but how do I merge this into a uri?
So I basically want
this.webBrowser1.Url = new Uri("file://" + directoryString + "myFolder/StoryBox/desert.html");
So if it ran it would be file://C:/Program Files (x86)/myFolder/StoryBox/desert.html);
P.S. I need it with the string incase the OS is 32 bit and it wont have the Program Files (x86) folder and I'm not writing C:/ incase they have a different drive name.
You almost have the answer in your question. Let me know if I'm missing something.
var folder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
var path = Path.Combine(folder, "myFolder/StoryBox/desert.html");
var uri = new Uri("file:" + path);

Capture the directory path it uses to run the program

I have a C# application which assume it runs from bin directory
string current_directory = Directory.GetCurrentDirectory(); //get current directory, this is the bin dir
string parent_dir = Directory.GetParent(current_directory).ToString();// this is parent of bin dir
string _Config1 = parent_dir + "\\config\\x.cfg";
string _Config2 = parent_dir + "\\config\\y.cfg";
string _Log = parent_dir + "\\log\\z.log";
The problem is for some reasons the user can not go to the bin directory and run the app (just type "application_name"). He has to run it using path (ie d:\blah\1\blah\2\blah\3\bin\application_name)
when he does this he gets
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Lo‌​cation)
so either I have to capture the path he uses to run the program and use it in my program or somehow make my application to be able to run using path.
You can use AppDomain.CurrentDomain.BaseDirectory.
Use the Application.StartupPath for WinForms.
You can use reflection:
var path = System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().GetCodebase );

Use relative Path in Microsoft Surface application?

I convert my wave file into a mp3 file by the following code:
internal bool convertToMp3()
{
string lameEXE = #"C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Concept_2\Prototype_Concept_2\lame\lame.exe";
string lameArgs = "-V2";
string wavFile = fileName;
string mp3File = fileName.Replace("wav", "mp3");
Process process = new Process();
process.StartInfo = new ProcessStartInfo();
process.StartInfo.FileName = lameEXE;
process.StartInfo.Arguments = string.Format("{0} {1} {2}", lameArgs, wavFile, mp3File);
process.Start();
process.WaitForExit();
int exitCode = process.ExitCode;
if (exitCode == 0)
{
return true;
}
else
{
return false;
}
}
This works, but now I'd like to not use the absolut path to the lame.exe but a relative path. I included a lame.exe in the folder /lame/ on the root of the project. How can I reference it?
If you have rights to distribute the file with your application, then one way of doing it would be to include the .exe file as an item in your C# project, with
Build Action = None
Copy to Output Directory = Copy if newer
You can then just use
string lameEXE = #"lame.exe"
Assuming your binary app is in Debug folder and the lame folder is in the main project directory:
string lameEXE = #"..\..\lame\lame.exe
Hovewer, folders structure will be probably different in your release version.
Directly using a path relative to the application directory is a bad idea since the working directory might not be identical to the application directory. This can lead to bugs and security holes. For example you might execute files in untrusted directories.
Some cases where the working directory isn't identical to the application directory:
The user opens a file from the explorer. Then the working directory is the directory where the file is in
Depending on the settings Common Dialogs(OpenFileDialog, SaveFileDialog) change the working directory.
So you should expand it relative to the project directory. Unfortunately I know of no clean library function which does that for you. In simple cases this can be done by concatenating the relative path to the application directory:
string appDir = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\";
const string relativePath=#"..\..\lame.exe";//Whatever relative path you want
string absolutePath=appDir+relativePath;
...
process.StartInfo.FileName =absolutePath;
...

Categories

Resources