I'm trying to open a file but I want it filter out to only .dat file.
using (OpenFileDialog fileChooser = new OpenFileDialog())
{
result = fileChooser.ShowDialog();
fileName = fileChooser.FileName; //Get file name.
fileChooser.Filter = "Data File|*.dat;";
fileChooser.DefaultExt = "dat";
fileChooser.AddExtension = true;
}
When having a OpenFileDialog in "using" the filter, defaultExt and Addextension doesn't work.
You should set filters before the call of "ShowDialog" method.
This should work.
using (var fileChooser = new OpenFileDialog())
{
// define the filters (first description | first filter; second description ...
fileChooser.Filter = "Data File|*.dat";
// select the first filter
fileChooser.FilterIndex = 1;
fileChooser.DefaultExt = "dat";
fileChooser.AddExtension = true;
// show the Opendialog
if (fileChooser.ShowDialog() == DialogResult.OK)
{
// get the path of specified file
var filename = fileChooser.FileName;
// use the filename to open the file...
}
}
Related
So I am converting an mp3 into wav, using NAudio
Example
string InputAudioFilePath = #"C:\Users\sdkca\Desktop\song.mp3";
string OutputAudioFilePath = #"C:\Users\sdkca\Desktop\song_converted.wav";
using (Mp3FileReader reader = new Mp3FileReader(InputAudioFilePath, wf => new Mp3FrameDecompressor(wf)))
{
WaveFileWriter.CreateWaveFile(OutputAudioFilePath, reader);
}
So in my view model, I am doing the following
I am getting the Documents folder
private static readonly string DocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Then I am doing this
const string ext = ".wav";
var dlg = new OpenFileDialog
{
Filter = Constants.FILEFILTER
};
var res = dlg.ShowDialog();
if (res! == true)
{
var AudioName = Path.GetFileNameWithoutExtension(dlg.FileName);
var FoderParent = Path.Combine(DocumentsPath, Constants.TRANSCRIPTIONS);
var ParentSubFolder = Path.Combine(FoderParent, Constants.AUDIO);
var filename = Path.Combine(ParentSubFolder, $"{AudioName}{ext}");
using var mp3 = new Mp3FileReader(dlg.FileName);
using var ws = WaveFormatConversionStream.CreatePcmStream(mp3);
WaveFileWriter.CreateWaveFile(filename, ws);
}
I am getting this error
System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Users\egome\OneDrive - Universidad Politécnica de Madrid\Documents\Transcriptions\Audio\10.wav'.'
What I do not understand is, that I am doing a combine between my folder and a new fileName.wav, that is required by the method
Add this check before creating filename string
if(!Directory.Exists(ParentSubFolder))
Directory.CreateDirectory(ParentSubFolder);
var filename = Path.Combine(ParentSubFolder, $"{AudioName}{ext}");
This way, you make sure all path parts exist.
I have created a software, which save some Information in an Excel File. The software has two possibilities:
To select the folder and then the software will create an Excel File with random name and there will save the data , or
To select an existed Excel File which is created from the user and there will save the data.
How to create a ONE ShowDialog to ask the user do you want to choose the folder or the file?!
Code that I have used to choose a Folder:
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
textBox3.Text = fbd.SelectedPath;
}
}
Code that I have used to choose a File:
OpenFileDialog excelFilename = new OpenFileDialog();
if (excelFilename.ShowDialog() == DialogResult.OK)
{
textBox3.Text = excelFilename.FileName;
}
Maybe something like this?:
MessageBoxResult result = MessageBox.Show("Ask user what he wants to do", "", MessageBoxButton.YesNo);
string path = null;
//MessageBoxResult.Yes means File, .No means Folder
if (result == MessageBoxResult.Yes)
{
//File-Picker
OpenFileDialog filePicker = new OpenFileDialog()
{
FileName = "Excel File",
DefaultExt = ".xls",
Filter = "Excel Document | *.xls"
};
if (filePicker.ShowDialog() == true)
{
path = filePicker.FileName;
}
}
else if (result == MessageBoxResult.No)
{
//Folder-Picker
CommonOpenFileDialog folderPicker = new CommonOpenFileDialog()
{
IsFolderPicker = true,
Multiselect = false
};
path = Path.Combine(folderPicker.FileName, DateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss"));
//Create file in folder
File.Create(path);
}
if (path != null)
{
// Do something with path (file user selected/program created)
}
Make sure you have the using System.Windows, using Microsoft.Win32; and using System.IO; using's at the beginning of your program.
You also have to add the WindowsAPICodePack library to your project to use the folder-picker. You can do that with the NuGet manager. Here's the link to the library: WindowsAPICodePack - 1.1.1
string filename = "";
private void openToolStripMenuItem1_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = #"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
lines = File.ReadAllLines(RecentFiles);
filename = theDialog.FileName;
for (int i = 0; i < lines.Length; i++)
{
recentfiles = new StreamWriter(RecentFiles, true);
recentfiles.WriteLine(theDialog.FileName);
recentfiles.Close();
items = File
.ReadLines(RecentFiles)
.Select(line => new ToolStripMenuItem()
{
Text = line
})
.ToArray();
recentFilesToolStripMenuItem.DropDownItems.AddRange(items);
}
TextFileContentToRichtextbox(filename);
}
}
I'm not sure if doing the for loop over the lines is right.
But what I want to do is when I open a new text file to check if it already exists in the RecentFiles(RecentFiles.txt) and if it does exist don't write it again.
Loop over lines and if after looping over all the lines and the variable filename does not exist then write it to the text file, and update the items.
Linq is perfect for this:
// if there are not any lines that equal the filename
if (!lines.Any(line => line.Equals(filename)))
{
// then write it into recent files text file
}
//// the below code will work only if a line has 1 fileName with extension or any text.
if (lines.Contains(filename, StringComparer.OrdinalIgnoreCase))
{
//// lines contains
}
else
{
////lines doesnot contain file name
}
Verify whether it full fill your requirement.
Use OpenFileDialogwith EPPlus. I get a compile error of:
The name 'sheet' does not exist in the current context
Now, the obvious issue is how do I associate the selected Excel file with my EPPPlus & 2 what do I do to remove the error above?
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
private void btn_ReadExcelToArray_Click(object sender, EventArgs e)
{
fd.Filter = "Excel Files|*.xlsx";
fd.InitialDirectory = #"C:\";
if (fd.ShowDialog() == DialogResult.OK)
{
var columnimport = sheet.Cells["A2:A"];
foreach (var cell in columnimport)
{
var column1CellValue = cell.GetValue<string>();
}
}
}
You are pretty close. All you have to do is create the package based on the stream (or you could use the fileinfo overload - either way). Like this:
var fd = new OpenFileDialog();
fd.Filter = "Excel Files|*.xlsx";
fd.InitialDirectory = #"C:\Temp\";
if (fd.ShowDialog() == DialogResult.OK)
{
using (var package = new ExcelPackage(fd.OpenFile()))
{
var sheet = package.Workbook.Worksheets.First();
var columnimport = sheet.Cells["A2:A"];
foreach (var cell in columnimport)
{
var column1CellValue = cell.GetValue<string>();
}
}
}
Is there any way i can take the data from the original location instead of copying the file to the bin/debug folder.
I am looking to send a file to my local printer. But my C# application is allowing to send file only when i copy the file to my bin/debug folder. Is there a way i can over come!!!
Codes:
private string image_print()
{
OpenFileDialog ofd = new OpenFileDialog();
{
InitialDirectory = #"C:\ZTOOLS\FONTS",
Filter = "GRF files (*.grf)|*.grf",
FilterIndex = 2,
RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK)
{
string filename_noext = Path.GetFileName(ofd.FileName);
string path = Path.GetFullPath(ofd.FileName);
img_path.Text = filename_noext;
string replacepath = #"bin\\Debug";
string fileName = Path.GetFileName(path);
string newpath = Path.Combine(replacepath, fileName);
if (!File.Exists(filename_noext))
{
// I don't like to copy the file to the debug folder
// is there an alternative solution?
File.Copy(path, newpath);
if (string.IsNullOrEmpty(img_path.Text))
{
return "";
}
StreamReader test2 = new StreamReader(img_path.Text);
string s = test2.ReadToEnd();
return s;
}
}
}
private void button4_Click(object sender, EventArgs e)
{
string s = image_print() + Print_image();
if (!String.IsNullOrEmpty(s) &&
!String.IsNullOrEmpty(img_path.Text))
{
PrintFactory.sendTextToLPT1(s);
}
}
Try this:
private string image_print()
{
string returnValue = string.Empty;
var ofd = new OpenFileDialog();
{
InitialDirectory = #"C:\ZTOOLS\FONTS",
Filter = "GRF files (*.grf)|*.grf",
FilterIndex = 2,
RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK &&
!string.IsNullOrWhiteSpace(ofd.FileName) &&
File.Exists(ofd.FileName))
{
img_path.Text = Path.GetFileName(ofd.FileName);
using (var test2 = new StreamReader(ofd.FileName))
{
returnValue = test2.ReadToEnd();
}
}
return returnValue;
}
It looks like the underlying issue is caused by these lines:
filename_noext = System.IO.Path.GetFileName(ofd.FileName); //this actually does include the extension!! It does not include the fully qualified path
...
img_path.Text = filename_noext;
...
StreamReader test2 = new StreamReader(img_path.Text);
You are getting the full file path from the OpenFileDialog then setting img_path.Text to just the file name. You are then using that filename (no path) to open the file for reading.
When you open a new StreamReader with just a filename it will look in the current directory for the file (relative to the location of the EXE, in this case bin/debug). Copying to "bin/debug" will probably not work in any other environment outside of your machine as the EXE will probably be deployed somewhere else.
You should use the full path to the selected file:
if (ofd.ShowDialog() == DialogResult.OK)
{
path = Path.GetFullPath(ofd.FileName);
img_path.Text = path;
if (string.IsNullOrEmpty(img_path.Text))
return "";//
StreamReader test2 = new StreamReader(img_path.Text);
string s = test2.ReadToEnd();
return s;
}