File Saveas or copy from xls to xlsx - vb.net

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));

Related

Code can create the directory but throws the exception `UnauthorizedAccessException` while copying the file to a directory

I am getting UnauthorizedAccessException while copying the file to a directory, inside the wwwroot. However Directory.CreateDirectory(uploadFolderPath); creates the folder.
The code I am using to create the folder and copy the files is shown below.
public string UploadPdfFile(IFormFile file, string folderName)
{
if (file == null || file.Length == 0)
{
return string.Empty;
}
// Define the file path
string uploadFolderPath = Path.Combine(_env.WebRootPath, #"uploads\books", $"{folderName}");
if (!Directory.Exists(uploadFolderPath))
Directory.CreateDirectory(uploadFolderPath);
// Save the file to the drive
using (var stream = new FileStream(uploadFolderPath, FileMode.Create))
{
file.CopyTo(stream);
}
return uploadFolderPath;
}
The error says:
UnauthorizedAccessException: Access to the path 'D:\Project\XX-Pedia\XX-Pedia\wwwroot\Uploads\Books\c1' is denied.
What is the solution for this?
I am running the visual studio in administrative mode.
This is strange because the code can create the folder but couldn't copy the files to the folder.
Turns out that I was missing the actual filename component...
string uploadFolderPath = Path.Combine(_env.WebRootPath, #"uploads\books", $"{folderName}");
if (!Directory.Exists(uploadFolderPath))
Directory.CreateDirectory(uploadFolderPath);
//added this line
string filepath = Path.Combine(uploadFolderPath, file.FileName);
// Save the file to the drive
using (var stream = new FileStream(filepath, FileMode.Create))
{
file.CopyTo(stream);
}

where is the created plugin (gtk) file?

I use the following script to create the plugin (gtk), but after I run the script, I do not know where is the created plugin (gtk) file?
I checked the folder
C:\Program Files (x86)\Gatan\DigitalMicrograph\PlugIns
I do not know see any new created gtk file in the folder.
Is this script wrong or the created gtk file should be in somewhere else?
/ Define the necessary variables string base,menu,submenu,item,packageNAME,name
number maxitem,i,j,maxfolder taggroup tgFILES,tgFOLDERS,tg
// Just some starting text in the results window.
result("\n Automatic Installation of all scripts in a folder as Plugin:\n\n")
// First get the default folder. (In this case, the folder last opened within DM)
base = GetApplicationDirectory(2,0)
// Prompt the user with a dialog to choose a folder, with the default folder as first choice.
// If the user cancels the dialog, the script will stop.
If (!GetDirectoryDialog("Please select the folder containing the scripts",base,base)) exit(0)
// Ask the user for a package name
If (!GetString("Name of package file?","",packageNAME)) exit(0)
// Ask the user for a menu name
If (!GetString("Name of menu to install the scripts in","",menu)) exit(0)
// Get all files/folders in the folder as a tag-list
tgFILES = GetFilesInDirectory(base,1)
tgFOLDERS = GetFilesInDirectory(base,2)
// Install all files from the main folder as menu commands.
// Count Items in the folder
maxitem = tgFILES.TagGroupCountTags()
i = 0
// Loop through all items
while (i<maxitem)
{
// get taggroup of item
tgFiles.TagGroupGetIndexedTagAsTagGroup(i,tg)
// get name of file
tg.TagGroupGetTagAsString("Name",item)
// Only if filename end with ".s" continue
If (right(item,2)==".s")
{
// use the name without the ending
name = left(item,len(item)-2)
result("\n Installing: "+item)
// install the menu command
// use the Try-Catch loop to detect problems during install
try
{ AddScriptToPackage(base+item,packageNAME,0,name,menu,"", 0) }
catch
{ result(" \t ERROR DURING INSTALL") } }
i++ }
// Now install all files from sub-folder as sub-menu commands.
// Count subfolders in the folder
maxfolder = tgFOLDERS.TagGroupCountTags()
// Loop for all subfolders
for (j=0;j<maxfolder;j++)
{
// get taggroup of item
tgFolders.TagGroupGetIndexedTagAsTagGroup(j,tg)
// get name of subfolder which is also the name of the submenu
tg.TagGroupGetTagAsString("Name",submenu)
// Get all files in the subfolder as a tag-list
tgFILES = GetFilesInDirectory(base+submenu,1)
// Count Items in the folder
maxitem = tgFILES.TagGroupCountTags()
i = 0
// Loop through all items as before for the main folder
while (i<maxitem)
{
tgFiles.TagGroupGetIndexedTagAsTagGroup(i,tg)
tg.TagGroupGetTagAsString("Name",item)
If (right(item,2)==".s")
{
name = left(item,len(item)-2)
result("\n Installing <"+submenu+">: "+item)
try {
AddScriptToPackage(base+item,packageNAME,0,name,menu,submenu, 0) }
catch
{
result(" \t ERROR DURING INSTALL") } }
i++ } }
You are probably running into the "Compatibility files" feature of Windows 7. GMS 1.x has only one variant of the AddScriptFileToPackage function and it always wants to save the resulting package file to the standard DM PlugIns folder:
C:\Program Files (x86)\Gatan\DigitalMicrograph\Plugins
But in Windows 7, such direct writing of files to subfolders of the Program Files directory is prevented and files are instead written to a user-specific local directory named as follows:
C:\Users\USERNAME\AppData\Local\VirtualStore\Program Files (x86)\Gatan\DigitalMicrograph\Plugins
However, one can easily make such virtualized files visible by clicking on the "Compatibility files" button that appears in the tool bar of the Windows explorer window for the standard PlugIns folder.
This depends a little on the GMS version and the OS version you're running on. I assume you're using GMS 2.x on a Windows7 or Windows8 machine, then the command AddScriptFileToPackage can have two syntax versions:
void AddScriptFileToPackage( String file_path, String packageName, Number packageLevel, String packageLocation, String command_name, String menu_name, String sub_menu_name, Boolean isLibrary )
void AddScriptFileToPackage( String file_path, String packageName, Number packageLevel, String command_name, String menu_name, String sub_menu_name, Boolean isLibrary )
in the first version packageLocation could be user_plugin or plugin. If this parameter is omitted (2nd command version) then user_plugin is assumed.
For user_plugin you will find the created file in:
C:\Users\USERNAME\AppData\Local\Gatan\Plugins
where USERNAME is the current windows user.
For plugin you will find the created file in the 'plugins' subfolder relative to the installation of the 'DigitalMicograph.exe', most likely in:
C:\Program Files\Gatan\Plugins

Setting openFileDialog to variable string

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 );

I can't extract files in program files folder

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

Upload file with meta data and checkin to sharpoint folder using Client Object Model

Hi I'm trying to upload a file to sharepoint 2010 using the client api with meta data and also checkin the file after I'm done. Below is my code:
public void UploadDocument(SharePointFolder folder, String filename, Boolean overwrite)
{
var fileInfo = new FileInfo(filename);
var targetLocation = String.Format("{0}{1}{2}", folder.ServerRelativeUrl,
Path.AltDirectorySeparatorChar, fileInfo.Name);
using (var fs = new FileStream(filename, FileMode.Open))
{
SPFile.SaveBinaryDirect(mClientContext, targetLocation, fs, overwrite);
}
// doesn't work
SPFile newFile = mRootWeb.GetFileByServerRelativeUrl(targetLocation);
mClientContext.Load(newFile);
mClientContext.ExecuteQuery();
//check out to make sure not to create multiple versions
newFile.CheckOut();
// use OverwriteCheckIn type to make sure not to create multiple versions
newFile.CheckIn("test", CheckinType.OverwriteCheckIn);
mClientContext.Load(newFile);
mClientContext.ExecuteQuery();
//SPFile uploadFile = mRootWeb.GetFileByServerRelativeUrl(targetLocation);
//uploadFile.CheckOut();
//uploadFile.CheckIn("SOME VERSION COMMENT I'D LIKE TO ADD", CheckinType.OverwriteCheckIn);
//mClientContext.ExecuteQuery();
}
I'm able to upload the file but I can't add any meta data and file is checked out. I want to add some meta data and checkin the file after I'm done.
My SharePointFolder class has the serverRelativeUrl of the folder path to upload to. Any help greatly appreciated.
You need a credential before the executeQuery(); and SaveBinaryDirect();
For example:
mClientContext.Credentials = new NetworkCredential("LoginID","LoginPW", "LoginDomain");
SPFile newFile = mRootWeb.GetFileByServerRelativeUrl(targetLocation);
mClientContext.Load(newFile);
mClientContext.ExecuteQuery();