exe saves file ok, except when launched via Excel macro - c#

I am new here
I have a c# program with WPF that
generates some pdf
saves it in the same directory
then opens the pdf for viewing
-->all that works fine with no error when exe launched directly.
But when the .exe is lauched by an excel macro (shell function) in an excel file in the same directory: excel macro is OK, program starts OK, generates the pdf OK, ... pdf is opened & viewed automatically OK (so makes me think the pdf was saved someghere)... and when all is closed ... not pdf in the directory !
It's probably an obvious general error, but I can't figure it out.
Detailed help appreciated as I am new to that
Fabrice

If Excel is using a different working directory, the file will be placed there and not where you expected. If this is the case, you can use the following method...
public string GetFullSaveName(string pdfName)
{
string myDirectoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (myDirectoryName != null)
{
string fullSaveName = Path.Combine(myDirectoryName, pdfName);
return fullSaveName;
}
throw new ApplicationException("Unable to locate assembly path");
}
This method uses Reflection to find out which directory your application is running in. It uses this to build up a fully qualified path so that your pdf file will be written to a predictable place. The path returned is the working directory of the application, and not Excel's.

Related

How to get the path of the uploaded file within the AppBundle?

We are using Autodesk Forge's Design Automation API. We have an AppBundle ready and we put an .rfa file into the same folder which contains the .dll file. When the AppBundle is unzipped on the Forge servers, which path can lead to our .rfa file? (how can we access it?) Our goal is to place the attached Family file's contents into the input file which is being uploaded with the API, and the result should be a new file which contains the additions from the file which we uploaded within the AppBundle. The process works when testing with Revit locally, but it doesn't work with the API. In the report we are retrieving it's obviously pointing out that the attached file cannot be found:
Autodesk.Revit.Exceptions.FileNotFoundException: T:\Aces\Jobs\ced628d35ecf4412b68c024e2cec098b\something.rfa
On the code side, we are trying to access the .rfa file via this path:
static string currentDir = Environment.CurrentDirectory;
static string path_input = currentDir+#"\something.rfa";
This seemed as a logical path, but as it turned out, it's not..
Is there a way to access the .rfa file inside the uploaded AppBundle?
I took a look at the Restrictions but reading the file from the AppBundle is not mentioned as restricted or not approachable. Am I missing something?
A .NET assembly knows its own path. You can call System.Reflection.Assembly.GetExecutingAssembly().Location within it to find the current path of the dll. You can then compute the path of the .rfa file relative to the folder of the dll and use it / open it. Thus you should be able to open any file you package along with your addin in your appbundle.
You can simply modify your code to:
static string assemblyLocation = Assembly.GetExecutingAssembly().Location;
static string assemblyDirectory = Path.GetDirectoryName(assemblyLocation);
static string path_input = assemblyDirectory+#"\something.rfa";
One thing to note however, is that you only have readonly access to files in appbundle. If your code relies on modifying these during execution, then you may simply copy the source rfa file to the current working folder and then work with the copied file instead.
Also see more details in blog for similar ideas.
We have a blog post on how you can either pass in the app bundle path in the commandLine parameter or find the path via the location of the add-in dll:
https://forge.autodesk.com/blog/store-template-documents-appbundle

C# Why does Process.Start("notepad.exe" myFile) is working and Process.Start("notepad++.exe" myFile) is not working

The code, in both case is identical:
This is working and opening the text file in notepad
editor = "notepad.exe";
if (File.Exists(briefingFile))
{
Process.Start(editor, briefingFile);
}
This one does is not work:
editor = "notepad++.exe";
if (File.Exists(briefingFile))
{
Process.Start(editor, briefingFile);
}
It is the same test file and I have notepad++ installed. I Also tried to specify notepad++ with full path but the result is the same.
Instead of opening notepad++ I get the attached error messages which tries to create new file or open missing files.
The notepad.exe file is part of Windows and lives in the Windows folder, which is part of the default search path (an environment variable). Notepad++.exe is not part of Windows, and so its home folder is not part of the default search path.
Therefore, to open a process using Notepad++ you must also know the full path to the program.
When trying the full path, make sure you escape the folder separator characters properly, and you must make sure to account for spaces in your path. In this case, the reason you see the C:\Program error is because you haven't yet accounted for the space in Program Files.
editor = #"""C:\Program Files\Notepad++\notepad++.exe""";
try
{
Process.Start(editor, briefingFile);
}
catch(Exception ex)
{
// Do something here
}
Also note how I switched to an exception handler instead of File.Exists(). Disk I/O is one of those rare places where you should prefer handling the exception. File.Exists() is particularly bad for this, and should be avoided.
One other option here is if you have enough control for your target machines to know for sure Notepad++ is even installed, then you also have enough control register it as the default program for the files types your using, meaning you can skip selecting a program name at all:
Process.Start(briefingFile);
The solution is to use double quotes in the text file, not in the application.
In my case:
change:
Process.Start(editor, briefingFile);
to
Process.Start(editor, $#"""{briefingFile}""");
The "editor" is a full path to the editor.
There is nothing wrong with your code, although, as Joel stated, there are drawbacks to using File.Exists(). You should only need to make sure that the Notepad++ folder is in your User/System Environment PATH variables. I added the path for my Notepad++ folder on this PC, which is just C:\Program Files\Notepad++\, and ran the same code and it opens the file in Notepad++ just fine.
I ran the below code in an empty .NET 3.1 forms project and it can execute just fine. Do you still get your error in a new project?
OpenFileDialog fileDialog= new OpenFileDialog();
fileDialog.Filter = "All Files (*.*)|*.*";
fileDialog.FilterIndex = 1;
string editor = "";
if (fialDialog.ShowDialog() == DialogResult.OK)
{
editor = fileDialog.FileName;
}
//Added the escaped quotes to the front & back of this in case the path contains spaces.
var filePath = #"""C:\SOMELOCALFILEPATH\test.txt""";
if (File.Exists(filePath))
{
Process.Start(editor, filePath);
}
I set a break point and my editor is in this format when Process.Start executes: "C:\\Program Files\\Notepad++\\notepad++.exe"
I ran into this issue and had also exactly same two errors when I tried to open a .txt file which was installed under C:\Program Files (x86)\MyProgram\SecondFolder\MyTxt.txt
The problem was when I copied the file path from windows explorer and pasted it into Visual Studio it deleted the blank space between Files and (x86).
happens when pasted directly into VS to edit it later. Can be avoided if you paste the path into quotation marks
You have to check if the file path is correct. Otherwise it won't work.

System.IO.FileNotFoundException when saving file on server

I know that this error has more awnsers on this form but none seem to be working since they are having problems with localhost. But localhost works fine for me.
I'm trying to create a .xlsx file from a button click on the server.
I already contacted the hosting company to make sure that it is possible to place files like this on there server and they told me that I could. So.... that is not the probleme.
This works perfect on localhost. But when I move it to the webhost I get this error:
I use this code:
using (var stream = new MemoryStream())
{
// local path
//string path = #"D:\local\Test\order.xlsx";
// Server path
string path = HostingEnvironment.MapPath(#"~\Excel-Exports\order.xlsx");
workbook.SaveAs(path);
var content = stream.ToArray();
File(
content,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"order.xlsx");
}
Before this part of code I build the Excel file. So I don't think that is the probleme.
I think the probleme is with the path since the tells me that I cant not find the file.
For the record I do use the same method for reaching a path on a different location and this works just fine.
Working code on other location
string path = HostingEnvironment.MapPath(#"~/img/MetropolisGO_RGB-kleur1.png");
LinkedResource Img = new LinkedResource(path);
Does anyone have a solution for me to save this file on the server?
The error indicates that the project is missing "ClosedXML" version 0.95.4 that is reference or using it but there is no DLL or library or project to be used.
If it's in your project, check the order of the building.
If is third-party, check the DLL or library is "copy always" in the build

Open PDF file from folder inside project in Windows Store App C#

I am working on Windows Store App. I have a folder named PDF in my solution in which I have one PDF file named "sample.pdf". I want to open that PDF file using code inside my application.
I have seen many links but could not find anything useful
Help?
You need to let the system open the file in the default viewer using LaunchFileAsync.
StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(#"PDF\file.pdf");
Windows.System.Launcher.LaunchFileAsync(file);

Can't extract .zip file. Getting Invalid Data Exception

I have a very large zip file which contains other zip files inside of it. I want my c# program to be able to recognize that the file is a zip file and if it is a zip file, then to extract it to a folder in the same location as the zip file. My code is here:
private void Unzip(OpenFileDialog tvZipOpen)
{
string zipFile = tvZipOpen.FileName; // file to unzip
int i = zipFile.LastIndexOf(".zip");
string targetDirectory = zipFile.Substring(0, i); // location to extract to
using (ZipArchive zip = ZipFile.OpenRead(zipFile))
{
zip.ExtractToDirectory(targetDirectory);
}
tvZipOpen.InitialDirectory = targetDirectory;
tvZipOpen.ShowDialog();
}
I am using the ZipFile class from .NET 4.5 and i call on this method here:
if (tvOpen.ShowDialog() == DialogResult.OK)
{
while (tvOpen.FileName.ToLower().EndsWith(".zip"))
{
Unzip(tvOpen);
}
return tvOpen.FileNames;
}
The code works fine for extracting the first zip file but when I try to extract the second zip file, I get an InvalidDataException that says local file header is corrupt. However, I don't think it is corrupt because I am able to open and extract the zip files perfectly in windows explorer. I'm not sure if the fact that it is a large zip file with a zip64 extension has anything to do with it but whatever the problem is, how come I don't get the problem when I open and extract in windows explorer and how do I fix this? Any help would be greatly appreciated.
c# does not support the .zip64 extension.
how large is your zip file because if it under 4GiB rename it to .zip and it should work fine if it is larger than that see this
http://dotnetzip.codeplex.com/
To change the file extension
Open windows explorer and press Alt + V
Then go to tools and then folder options and make sure that the hide extensions for known file types box is unchecked and click apply and ok.
then simply rename the file to remove the 64 from the extension so it is just .zip
Then Click yes on the prompt
And then you should be able to open the file in your program
hope this helps

Categories

Resources