I am using the below code in C# in a WPF Application
I am using this method to save one file to disk:
private void executeSaveAttachment(object parameter)
{
SaveFileDialog dlg = new SaveFileDialog();
{
dlg.AddExtension = true;
dlg.DefaultExt = "xlsx";
dlg.Filter = "New Excel(*.xlsx)|*.*";
foreach (var table in Table)
{
if (dlg.ShowDialog() ?? false)
{
File.WriteAllBytes(dlg.FileName, table.Data);
}
}
}
}
I am trying to use this method to store multiple files to a location the user is able to choose but give it default filename from the Title Property and add .xlsx extension. The class is named Table and the Data Property is the binary.
Here is the method that is giving
Error 4 No overload for method 'WriteAllBytes' takes 1 arguments
private void executeSaveAttachments(object parameter)
{
{
System.Windows.Forms.FolderBrowserDialog flg = new System.Windows.Forms.FolderBrowserDialog();
foreach (var table in Table)
{
if (flg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllBytes(Path.Combine(flg.SelectedPath, table.Title + ".dat"));
}
}
}
}
As the error suggests, WriteAllBytes doesn't have an overload with one argument. You must specify the bytes to write, as well as the path. You have it right in your first block so simply do the same again:
File.WriteAllBytes(Path.Combine(flg.SelectedPath, table.Title + ".dat"), table.Data);
You are missing an argument and you aren't passing data to write to your location. Path.Combine(flg.SelectedPath, table.Title + ".dat") is one argument, you forgot to pass the second argument.
File.WriteAllBytes(
Path.Combine(flg.SelectedPath, table.Title + ".dat"),
table.Data
);
Related
I'm trying to upload multiple files and just get the filename of them.
When I'm trying to do that it just uploads one file.
So it uploads the files with the full path(And it works).
private void bChooseFolder_Click(object sender, EventArgs e)
{
CoreClass.OPENDIALOG.Multiselect = true;
string oldFilter = CoreClass.OPENDIALOG.Filter;
CoreClass.OPENDIALOG.Filter = "(*.csv) | *.csv";
if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK)
tbFolderPath.Text = string.Join(FileSeperator, CoreClass.OPENDIALOG.FileNames);// <-- this works, but here I get the full path
CoreClass.OPENDIALOG.Filter = oldFilter;
CoreClass.OPENDIALOG.Multiselect = false;
}
And so I get just the Filename but it uploads just one File:
private void bChooseFolder_Click(object sender, EventArgs e)
{
CoreClass.OPENDIALOG.Multiselect = true;
string oldFilter = CoreClass.OPENDIALOG.Filter;
CoreClass.OPENDIALOG.Filter = "(*.csv) | *.csv";
if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK)
tbFolderPath.Text = string.Join(FileSeperator, System.IO.Path.GetFileNameWithoutExtension(CoreClass.OPENDIALOG.FileName)); // <-- Doesn't work. Just one File.
CoreClass.OPENDIALOG.Filter = oldFilter;
CoreClass.OPENDIALOG.Multiselect = false;
}
OK, If you are developing WinForms app then you are using OpenFileDialog which contains 2 properties:
FileName gets or sets a string containing the file name selected in the file dialog box.
FileNames gets the file names of all selected files in the dialog box.
Then first one will never contains few files and you should use it only in Multiselect = false; mode.
If you need to show all file names in one textbox then you can use String.Join method and LINQ to enumerate collection and get file name without extension for each element:
if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK)
tbFolderPath.Text = string.Join(FileSeperator, CoreClass.OPENDIALOG.FileNames.Select(x => System.IO.Path.GetFileNameWithoutExtension(x)).ToArray()); // <-- Doesn't work. Just one File.
I have recently started to get an error which states my directory can not be found I have tried a number of ways to solve this but have yet to find a solution.
The method should allow the user to select an image for their computer and add it to a folder called images inside the applications folder structure. The problem is that when using the File.copy(imageFilename, path); it throws the error. I have tried changing the path and you will see from the code snip it. It is even doing it when the program itself has passed the file path for the application and is still throwing me the error.
this is the method.
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
System.IO.File.Copy(imageFile.FileName, path);
}
}
}
I am using VS2013 and have included the using Microsoft.win32
Any further information needed please ask.
Thanks
There are 2 things need to be taken into consideration
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
string path = AppDomain.CurrentDomain.BaseDirectory; // You wont need it
System.IO.File.Copy(imageFile.FileName, path); // Copy Needs Source File Name and Destination File Name
}
}
}
string path = AppDomain.CurrentDomain.BaseDirectory; You won need this because the default directory is your current directory where your program is running.
Secondly
System.IO.File.Copy(imageFile.FileName, path); Copy Needs Source File Name and Destination File Name so you just need to give the file name instead of path
so your updated code will be
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
System.IO.File.Copy(imageFile.FileName, SomeName + ".jpg"); // SomeName Must change everytime like ID or something
}
}
}
I'm not sure if that's the problem, but the File.Copy method expects a source file name and a target file name, not a source file name and directory: https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx
So, to make this work, in your case you'd have to do something like the following (namespaces omitted):
File.Copy(imageFile.FileName, Path.Combine(path, Path.GetFileName(imageFile.FileName));
Note that this will fail if the destination file exists, to overwrite it, you need to add an extra parameter to the Copy method (true).
EDIT:
Just a note, the OpenFileDialog.CheckFileExists does not return a value indicating if the selected file exists. Instead, it is a value indicating whether a file dialog displays a warning if the user specifies a file name that does not exist. So instead of checking this property after the dialog is closed, you should set it to true before you open it (https://msdn.microsoft.com/en-us/library/microsoft.win32.filedialog.checkfileexists(v=vs.110).aspx)
I am developing an application and I need to read the EXIF details of JPG file.
I am able to do so with an OpenFileDialog button but, I want it to be so that a user can open a JPG file with my application (right click>Open with) and I could get the path of the JPG file in string.
I just want to know how to get the path of the file on which the user right clicked ad selected open with "My Application"
You need to register your application for the JPG file extension in the Registry as described here: https://msdn.microsoft.com/en-us/library/windows/desktop/cc144175(v=vs.85).aspx
If you know how to get the EXIF data already and just want users to be able to right-click a JPG file > Open with > Select your application and then get the filename they're trying to open, you can do this:
private void testButton_Click(object sender, EventArgs e)
{
string[] cmdLineArgs = Environment.GetCommandLineArgs();
string jpgFilenameToOpen = "None";
if (cmdLineArgs.Length > 1)
{
jpgFilenameToOpen = cmdLineArgs[1];
}
YourGetEXIFDetailsMethod(jpgFilenameToOpen);
}
The Environment.GetCommandLineArgs() returns an array with all command line arguments that was passed to your application on load. Normally, if they just pass a filename, it should be the 2nd item in the array.
You can also loop through the arguments if needed by doing this:
foreach (var arg in cmdLineArgs)
{
MessageBox.Show(arg.ToString());
}
Edit:
I just realized I'm not sure if you need to accept only one JPG filename at a time or if you need to accept multiple JPG files at once. If it's the latter, here's some updated code that can loop through all the command-line arguments and do something with only JPG/JPEG files:
private void Form1_Load(object sender, EventArgs e)
{
string[] cmdLineArgs = Environment.GetCommandLineArgs();
List<string> jpgFilenamesToAnalyze = new List<string>();
foreach (var arg in cmdLineArgs)
{
if (arg.Contains(".jpg") || arg.Contains(".jpeg"))
{
jpgFilenamesToAnalyze.Add(arg);
}
}
if (jpgFilenamesToAnalyze.Count > 0)
{
StringBuilder sbJPGFiles = new StringBuilder();
sbJPGFiles.AppendLine("Found " + jpgFilenamesToAnalyze.Count + " images to analyze:\n\nFiles:");
foreach (var jpgFilename in jpgFilenamesToAnalyze)
{
// YourGetEXIFDataMethod(jpgFilename)
sbJPGFiles.AppendLine(jpgFilename);
}
MessageBox.Show(sbJPGFiles.ToString());
}
else
{
MessageBox.Show("No images found to analyze");
}
}
I am working on selecting a text file with a folder pathway via a Windows form in C# and gathering information on each pathway. At the minute, I can import the file and display only the second pathway in the text file, but no information on the folder. Here is the code I have:
private void btnFilePath_Click(object sender, EventArgs e)
{
//creating a stream and setting its value to null
Stream myStream = null;
//allowing the user select the file by searching for it
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = "c:\\";
open.Filter = "txt files (*.txt)|*.txt";
open.FilterIndex = 2;
open.RestoreDirectory = true;
//if statement to print the contents of the file to the text box
if (open.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = open.OpenFile()) != null)
{
using (myStream)
{
txtFilePath.Text = string.Format("{0}", open.FileName);
if (txtFilePath.Text != "")
{
lstFileContents.Text = System.IO.File.ReadAllText(txtFilePath.Text);
//counting the lines in the text file
using (var input = File.OpenText(txtFilePath.Text))
{
while (input.ReadLine() != null)
{
//getting the info
lstFileContents.Items.Add("" + pathway);
pathway = input.ReadLine();
getSize();
getFiles();
getFolders();
getInfo();
result++;
}
MessageBox.Show("The number of lines is: " + result, "");
lstFileContents.Items.Add(result);
}
}
else
{
//display a message box if there is no address
MessageBox.Show("Enter a valid address.", "Not a valid address.");
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read the file from disk. Original error: " + ex.Message);
}
}
}
I was thinking that copying each line to a variable using a foreach or putting each line into an array and looping through it to gather the information.
Can anyone advise me which would be most suitable so I can go to MSDN and learn for myself, because, I'd prefer to learn it instead of being given the code.
Thanks!
I am not sure what your question is since you seemed to have answered it. If you want us to review it you question would be better suited to Code Review: https://codereview.stackexchange.com/
If you want to use MSDN look here: http://msdn.microsoft.com/en-us/library/System.IO.File_methods(v=vs.110).aspx
Spoiler alert, here is how I would do it:
string[] lines = null;
try
{
lines = File.ReadAllLines(path);
}
catch(Exception ex)
{
// inform user or log depending on your usage scenario
}
if(lines != null)
{
// do something with lines
}
to just gather all lines into array i would use
var lines = File.ReadAllLines(path);
If you want to have more reference rather than the answer itself, take these links one by one all of them explaining things in different manner.
C# File.ReadLines
How to: Read From a Text File (C# Programming Guide)
How to: Read a Text File One Line at a Time (Visual C#)
Hope it will help you to learn more about File IO operations in C#.
I have a requirement in WPF/C# to click on a button, gather some data and then put it in a text file that the user can download to their machine. I can get the first half of this, but how do you prompt a user with a "Save As" dialog box? The file itself will be a simple text file.
Both answers thus far link to the Silverlight SaveFileDialogclass; the WPF variant is quite a bit different and differing namespace.
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
}
SaveFileDialog is in the Microsoft.Win32 namespace - might save you the 10 minutes it took me to figure this out.
Here is some sample code:
string fileText = "Your output text";
SaveFileDialog dialog = new SaveFileDialog()
{
Filter = "Text Files(*.txt)|*.txt|All(*.*)|*"
};
if (dialog.ShowDialog() == true)
{
File.WriteAllText(dialog.FileName, fileText);
}
Use the SaveFileDialog class.
You just need to create a SaveFileDialog, and call its ShowDialog method.
All the examples so far use the Win32 namespace, but there is an alternative:
FileInfo file = new FileInfo("image.jpg");
var dialog = new System.Windows.Forms.SaveFileDialog();
dialog.FileName = file.Name;
dialog.DefaultExt = file.Extension;
dialog.Filter = string.Format("{0} images ({1})|*{1}|All files (*.*)|*.*",
file.Extension.Substring(1).Capitalize(),
file.Extension);
dialog.InitialDirectory = file.DirectoryName;
System.Windows.Forms.DialogResult result = dialog.ShowDialog(this.GetIWin32Window());
if (result == System.Windows.Forms.DialogResult.OK)
{
}
I'm using an extension method to get the IWin32Window from the visual control:
#region Get Win32 Handle from control
public static System.Windows.Forms.IWin32Window GetIWin32Window(this System.Windows.Media.Visual visual)
{
var source = System.Windows.PresentationSource.FromVisual(visual) as System.Windows.Interop.HwndSource;
System.Windows.Forms.IWin32Window win = new OldWindow(source.Handle);
return win;
}
private class OldWindow : System.Windows.Forms.IWin32Window
{
private readonly System.IntPtr _handle;
public OldWindow(System.IntPtr handle)
{
_handle = handle;
}
System.IntPtr System.Windows.Forms.IWin32Window.Handle
{
get { return _handle; }
}
}
#endregion
Capitalize() is also an extension method, but not worth mentioning as there are plenty of examples of capitalizing the first letter of a string out there.