I am trying to create a small GUI that will rename a file (eventually a batch of files). I am using C++ and Windows user (Visual Studio Community 2015).
I have a btnSelectFiles button with which I want to open a file selection GUI.
I am trying to use openFileDialog but am struggling to set the file name to a string variable.
The code I am using:
public:
void btnSelectFiles_Click(Object^ /*sender*/, System::EventArgs^ /*e*/)
{
IO::Stream^ myStream;
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
openFileDialog1->InitialDirectory = "c:\\";
openFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1->FilterIndex = 2;
openFileDialog1->RestoreDirectory = true;
if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
if ((myStream = openFileDialog1->OpenFile()) != nullptr)
{
// Insert code to read the stream here.
myStream->Close();
}
}
/*String test = openFileDialog1;*/
}
One of my many tries was to use:
String test = openFileDialog1
I also tried:
String test = openFileDialog1.FileName
But received an expression must have class type error.
Please can someone help me solve this and thus help my understanding on the matter. The book I have picked up does not cover this and I have struggled to find help online.
Since you are using c++/CLI ( rather than C++ ) you must write
String^ test = new String( openFileDialog1.FileName );
Related
I have an excel file in the C disk named C:\Book1.xls
How can I saveas C:\Book1.xls to C:\Book2.xlsx ?
Is there a System.IO.File.SaveAs class?
The following code doesnt work;
IO.File.Copy(sourceFileName:="C:\Book1.xls", destFileName:="C:\Book1.xlsx", overwrite:=True)
Edit: I dont want to use Excel Interop because of Microsoft Office versions.
You can use this nuget package for converting your current xls document to xlsx.
Something like this will work for you :
Workbook workbook = new Workbook();
workbook.LoadFromFile("Book1.xls");
workbook.SaveToFile("Book2.xlsx", ExcelVersion.Version2016);
This is the main page of package that you may find more details.
Another possible option - just copy the file using a process in C#, create a process to copy the file from xls to xlsx. No fuss, no muss. This is in .Net Core 6.0 and o365.
Ultimately, the string you are running in the process (aka command prompt) should look similar to this:
"C:\Program Files (x86)\Microsoft Office\root\Office16\excelcnv.exe"
-oice "\Share\Folder\Cash.xls" "\Share\Folder\Cash.xlsx"
public static class Xls2XlsxCmdProcess
{
public static string processDirectory = #"C:\Program Files (x86)\Microsoft Office\root\Office16\";
public static void ExecuteCommandSync(string pathToExe, string command)
{
var procStartInfo = new ProcessStartInfo(pathToExe, command)
{
WorkingDirectory = processDirectory,
CreateNoWindow = false,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true
};
var proc = new Process { StartInfo = procStartInfo };
proc.Start();
//proc.StandardInput.WriteLine(password);//If the app that requires a password or other params, they can be added here as a string.
proc.StandardInput.Flush();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
string error = proc.StandardError.ReadToEnd();
Console.WriteLine(result);
Console.WriteLine(error);
}
}
To call it, specify all your params, your working directory, and you're off to the races!!!
string baseFolder = #"\\Share\folder\";
string fileNameCash = "Cash.xls";
string fileNameCashOutput = "Cash.xlsx";
//Create cash as xlsx files (for ease of use with EPPlus4)
string pathToExe = #"C:\Program Files (x86)\Microsoft Office\root\Office16\excelcnv.exe";//Path to office XLS to XLSX Conversion Tool for o365 - You can find a similar version by searching for the excelcnv.exe within "C:\Program Files (x86)\Microsoft Office" folder.
string commandFormat1 = string.Format(#"""{0}"" -oice ""{1}{2}"" ""{3}{4}"" ",pathToExe, #BaseFolder, fileNameCash,#BaseFolder,fileNameCashOutput);
Xls2XlsxCmdProcess.ExecuteCommandSync(pathToExe, string.Format(commandFormat1));
I can't get Process.Start to simply launch a PDF with default PDF viewer.
I tried so many combinations of shell execute, working folder etc etc. Keeps giving me either 'The system cannot find the file specified' or 'the directory name is invalid'
private void button1_Click(object sender, EventArgs e)
{
string filename = #"Milking and cooling software set 2018-39.pdf";
MessageBox.Show(currentpath + #"\Astronaut A5 v1.5(b7)\documentation\" + filename);
fullpath = currentpath + #"\Astronaut A5 v1.5(b7)\documentation";
fullfile = fullpath + filename;
ProcessStartInfo process = new ProcessStartInfo();
process.WorkingDirectory = fullpath;
process.UseShellExecute = false;
process.FileName = fullfile;
process.RedirectStandardOutput = true;
process.Verb = "run as";
Process.Start(process);
}
Why is this so hard, I have tried for hours to simply lauch Acrobat Reader to open a PDF file. I can double click it no problem in it's location but C# can't open it, either I get .NET errors or Adobe opens and says it can't find the file. Tried so many combinations of "\"", full path, hard coded path etc etc...unbelievable that this is so hard to code in this day and age.
You’ve told the system to not use ShellExecute. This means the path you’re giving should be an actual executable program. PDFs are not so if you want to open it with the default reader use ShellExecute.
process.UseShellExecute = true;
Also using “run as” as the verb doesn’t make any sense here, unless there is such a verb defined for PDFs which I’m pretty sure there isn’t. That should be removed.
I'm working on custom action and wix.The files are not extracting in program files (x86) folder.But the files are extracting correctly other than program files (x86). I have written code using .NET FRAMEWORK 4.0.
namespace Installer
{
public class CustomActions
{
[CustomAction]
public static ActionResult CustomAction1(Session session)
{
session.Log("Begin Extracting");
string FinalPath = session["APPDIR"];``
string zPath = #"C:\Users\AppData\Local\Temp\Install\7za.exe";
string ExtractPath = #"C:\Program Files (x86)\Samples\";
string sourcePath = #"C:\Program Files (x86)\Samples\source.zip";
try`
{
ProcessStartInfo pro = new ProcessStartInfo();``
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = zPath;
pro.Arguments = "x \"" + sourcePath + "\" -o" + ExtractPath;
Process x = Process.Start(pro);
x.WaitForExit();
}
catch (System.Exception Ex)
{
}
return ActionResult.Success;
}
}
}
First of all you need to debug it properly. You're throwing away any error that might be thrown. Sorry to say this, but your question is unfortunately more like "how can I find out why my code is not working when I've thrown away any exceptions it might raise?"
There's no guarantee that the zip extension will work correctly just by starting it. It might work if WinZip is installed, but not if all that happens is that Explorer opens to look at the files.
You should use the classes that will unzip it. Example here:
https://msdn.microsoft.com/en-us/library/ms404280(v=vs.110).aspx
I have been trying to find the best way to do this I have thought of extracting the contents of the .jar then moving the files into the directory then putting it back as a jar. Im not sure is the best solution or how I will do it. I have looked at DotNetZip & SharpZipLib but don't know what one to use.
If anyone can give me a link to the code on how to do this it would be appreciated.
For DotNetZip you can find very simple VB.NET examples of both creating a zip archive and extracting a zip archive into a directory here. Just remember to save the compressed file with extension .jar .
For SharpZipLib there are somewhat more comprehensive examples of archive creation and extraction here.
If none of these libraries manage to extract the full JAR archive, you could also consider accessing a more full-fledged compression software such as 7-zip, either starting it as a separate process using Process.Start or using its COM interface to access the relevant methods in the 7za.dll. More information on COM usage can be found here.
I think you are working with Minecraft 1.3.1 no? If you are, there is a file contained in the zip called aux.class, which unfortunately is a reserved filename in windows. I've been trying to automate the process of modding, while manipulating the jar file myself, and have had little success. The only option I have yet to explore is find a way to extract the contents of the jar file to a temporary location, while watching for that exception. When it occurs, rename the file to a temp name, extract and move on. Then while recreating the zip file, give the file the original name in the archive. From my own experience, SharZipLib doesnt do what you need it do nicely, or at least I couldnt figure out how. I suggest using Ionic Zip (Dot Net Zip) instead, and trying the rename route on the offending files. In addition, I also posted a question about this. You can see how far I got at Extract zip entries to another Zip file
Edit - I tested out .net zip more (available from http://dotnetzip.codeplex.com/), and heres what you need. I imagine it will work with any zip file that contains reserved file names. I know its in C#, but hey cant do all the work for ya :P
public static void CopyToZip(string inArchive, string outArchive, string tempPath)
{
ZipFile inZip = null;
ZipFile outZip = null;
try
{
inZip = new ZipFile(inArchive);
outZip = new ZipFile(outArchive);
List<string> tempNames = new List<string>();
List<string> originalNames = new List<string>();
int I = 0;
foreach (ZipEntry entry in inZip)
{
if (!entry.IsDirectory)
{
string tempName = Path.Combine(tempPath, "tmp.tmp");
string oldName = entry.FileName;
byte[] buffer = new byte[4026];
Stream inStream = null;
FileStream stream = null;
try
{
inStream = entry.OpenReader();
stream = new FileStream(tempName, FileMode.Create, FileAccess.ReadWrite);
int size = 0;
while ((size = inStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, size);
}
inStream.Close();
stream.Flush();
stream.Close();
inStream = new FileStream(tempName, FileMode.Open, FileAccess.Read);
outZip.AddEntry(oldName, inStream);
outZip.Save();
}
catch (Exception exe)
{
throw exe;
}
finally
{
try { inStream.Close(); }
catch (Exception ignore) { }
try { stream.Close(); }
catch (Exception ignore) { }
}
}
}
}
catch (Exception e)
{
throw e;
}
}
I've been trying to read a pre-built file with Car Maintenance tips, there's one in each line of my "Tips.txt" file. I've tried to follow around 4 or 5 different approaches but It's not working, it compiles but I get an exception. Here's what I've got:
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamReader sr = new StreamReader(store.OpenFile("Tips.txt", FileMode.Open, FileAccess.Read)))
{
string line;
while ((line = sr.ReadLine()) != null)
{
(App.Current as App).MyTips.Insert(new DoubleNode(line));
}
}
}
I'm getting this "Operation not permitted on IsolatedStorageFileStream", from the info inside the 2nd using statement. I tried with the build action of my "Tips.txt" set to resource, and content, yet I get the same result.
Thanks in advance.
Since you've added it to your project directory, you can't read it using Isolated Storage methods. There are various ways you can load the file. One way would be to set the text file's build type to Resource, then read it in as a stream:
//Replace 'MyProject' with the name of your XAP/Project
Stream txtStream = Application.GetResourceStream(new Uri("/MyProject;component/myTextFile.txt",
UriKind.Relative)).Stream;
using(StreamReader sr = new StreamReader(txtStream))
{
//your code
}