I am new to c# and I am almost done with a simple project. This project needs to include an excel file available for download using a LinkLabel
How can I include this file when compiling my project and when the LinkLabel is click it will as the user where to save the file.
My google search always point me to creating an excel, I dont need to create it, its already available, i just need to include in my resource file.
I am stuck here;
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
}
Now its working fine with the below code, I cant answer my question yet due to low score.
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string filePath = null;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
filePath = saveFileDialog1.FileName;
File.WriteAllBytes(#filePath, Properties.Resources.importPurchases);
MessageBox.Show("File Successfully saved.\r\n\r\n" + filePath, "Success Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
return;
}
}
Add the excel file to your Project (Add -> Existing Item).
Right Click the added Excel File, go to Properties
Set Build Action to Content
Set Copy to Output Directory as Copy Always or Copy If Newer
By doing this; the Excel File would be copied to the output folder always after build.
var saveFileDialog = new SaveFileDialog();
saveFileDialog.DefaultExt = "xls";
saveFileDialog.Filter = "Excel files (*.xls)|*.xls |All files (*.*)|*.*";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
const string MyFileName = "myExcelFile.xls";
string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
var filePath = Path.Combine(execPath, MyFileName);
Microsoft.Office.Interop.Excel.Application app = new Application();
Microsoft.Office.Interop.Excel.Workbook book = app.Workbooks.Open(filePath);
book.SaveAs(saveFileDialog.FileName); //Save
book.Close();
}
Update: The above sample is for Windows Application...
Related
Using Visual Studio 2017 and Windows 10 I want to be able to open a file explorer and navigate to a file outside of the program. Once my file is collected I want to get the file path and the complete file name for the file explorer.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "All files (*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
textBoxFolderpath.Text= openFileDialog1.FileName;
if (textBoxFolderpath.Text.Contains('\\'))
textBoxFolderpath.Text = textBoxFolderpath.Text.Substring(0, textBoxFolderpath.Text.LastIndexOf('\\'));
This is what I have tried so far. The textBoxFolderpath is being used to hold the values.
What am I missing or doing incorrectly?
When working with filenames and paths I'd highly recommend using built-in classes to handle this, like the Path class:
Path.GetDirectoryName(openFileDialog1.FileName)
This returns the path, without the filename. It's also cross-platform compatible.
Thanks Zer0 - below is what I ended up using.
private void btnCurrentFolder_Click(object sender, EventArgs e)
{
OpenFileDialog openDialog1 = new OpenFileDialog();
// Determine starting directory
if (chkSetToRoot.Checked)
{
openDialog1.InitialDirectory = #"K:\RESULTS";
}
openDialog1.Title = "Select A Test File";
openDialog1.Filter = "All Files (*.*)|*.*";
if (openDialog1.ShowDialog() == DialogResult.OK)
{
textBoxFolderpath.Text = Path.GetDirectoryName(openDialog1.FileName);
textBoxFileName.Text = Path.GetFileName(openDialog1.FileName);
}
}
I am attempting to copy a .txt from my application directory or some kind an export feature to users desire path and filename using savedialog on C# my code is below.
private void button2_Click(object sender, EventArgs e)
{
string directory = AppDomain.CurrentDomain.BaseDirectory + "output.txt";
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.Filter = "txt files (*.txt);
dialog.FilterIndex = 2;
dialog.RestoreDirectory = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
File.Copy(directory, Path.GetDirectoryName(dialog.FileName) + dialog.FileName);
}
}
}
But I am getting an error
The given path's format is not supported.
I am new with C# and want to understand this error and in addition, I want to set the file name extention default as .txt also, any suggestion would be great.
There are a couple of things you need to change.
First, of course, is your copy call. This line makes no sense
File.Copy(directory, Path.GetDirectoryName(dialog.FileName) + dialog.FileName);
dialog.FileName contains already the full file name of your destination file. So there is no need to extract the directory and then add all the path again. Write just
File.Copy(directory, dialog.FileName);
But this creates a possible error. What if your user doesn't change the destination folder to another directory? You end up writing on the same file you want to read.
So I would add a sanity check like this
if(directory == dialog.FileName)
MessageBox.Show("Copy","Choose a different output folder");
else
File.Copy(directory, dialog.FileName);
Finally, if you want to force the output file to have always the .TXT extension you could add this line to the SaveDialog configuration
// Fix also your filter property. The one you have is invalid
dialog.Filter = "txt files (*.txt)|*.txt";
dialog.FilterIndex = 0; // 2 ?? There is no index 2 in your filter string
dialog.RestoreDirectory = true;
// Force the .TXT extension
dialog.AddExtension = true;
my program has a save file option which is shown below :
//Browse for file
SaveFileDialog ofd = new SaveFileDialog();
ofd.Filter = "CSV|*.csv";
ofd.DefaultExt = ".csv";
DialogResult result = ofd.ShowDialog();
string converted = result.ToString();
if (converted == "OK")
{
Master_Inventory_Export_savePath.Text = ofd.FileName;
}
if I write the file name as "example" it saves correctly as a .csv however if I set the name as "example.txt" it saves as a text file , I've looked on msdn etc but even setting the default extension doesn't prevent this , any ideas on how to only allow files of .csv to be saved ?
You could use the FileOk event to check what your user types and refuse the input if it types something that you don't like.
For example:
SaveFileDialog sdlg = new SaveFileDialog();
sdlg.FileOk += CheckIfFileHasCorrectExtension;
sdlg.Filter = "CSV Files (*.csv)|*.csv";
if(sdlg.ShowDialog() == DialogResult.OK)
Console.WriteLine("Save file:" + sdlg.FileName);
void CheckIfFileHasCorrectExtension(object sender, CancelEventArgs e)
{
SaveFileDialog sv = (sender as SaveFileDialog);
if(Path.GetExtension(sv.FileName).ToLower() != ".csv")
{
e.Cancel = true;
MessageBox.Show("Please omit the extension or use 'CSV'");
return;
}
}
The main advantage of this approach is that your SaveFileDialog is not dismissed and you could check the input without reloading the SaveFileDialog if something is wrong.
BEWARE that the SaveFileDialog appends automatically your extension if it doesn't recognize the extension typed by your user. This means that if your user types somefile.doc then the SaveFileDialog doesn't append the .CSV extension because the .DOC extension is probably well known in the OS. But if your user types somefile.zxc then you receive as output (and also in the FileOk event) a FileName called somefile.zxc.csv
can you not just force the .csv filetype by going like so in the last block of code?
if (converted == "OK")
{
if (ofd.FileName.toString.EndsWith(".csv")<1)
{
Master_Inventory_Export_savePath.Text = ofd.FileName + ".csv";
}
else
{
Master_Inventory_Export_savePath.Text = ofd.FileName;
}
}
Note - untested, but should give you a starting point....
Set the property AddExtension to true.
ofd.AddExtension = true;
I am using following code to select a file to import in a Windows Forms project.
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog";
fdlg.InitialDirectory = #"c:\";
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
txtpath.Text = fdlg.FileName;
}
The problem is that the selected file is opened in the background which I don't want. What can I do to just get the path of selected file without opening it?
Showing an OpenFileDialog and the user selecting a file does not open the file. The file can be opened by calling OpenFile. In the code you posted the file is not opened. That code appears to be copied from an example on MSDN. The rest of the code from that example is here:
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null) // File is opened here.
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " +
ex.Message);
}
}
If the file is being opened when you don't want it opened then the problem must be somewhere else and not in the code you posted. It is possible for example that you have not closed the file (for example by using Dispose) after you finished using it last time.
I am using my own Custom View to show the files and folders and also using a search box to jump to a specific folder. In that case How to send a message to File Open/Save dialog to enforce it to change the current displayed folder.
e.g. If the dialog shows files and folders of current displaying folder "C:\", I want an API (or any piece of code) to enforce to change the current folder to "D:\"
You can have the dialog open at a specific directory using InitialDirectory.
If you want to control what the dialog does at runtime, that's a bit more complex.
Set SaveFileDialog.InitialDirectory after you create it, but before you open it.
For example:
Stream myStream = null;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1 .InitialDirectory = "d:\\" ;
saveFileDialog1 .Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1 .FilterIndex = 2 ;
saveFileDialog1 .RestoreDirectory = true ;
if(saveFileDialog1 .ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = saveFileDialog1 .OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not save file to disk. Original error: " + ex.Message);
}
}
set InitialDirectory property to any path