How can I get the filesize of the currently-selected file in my Openfiledialog?
You can't directly get it from the OpenFieldDialog.
You need to take the file path and consturct a new FileInfo object from it like this:
var fileInfo = new FileInfo(path);
And from the FileInto you can get the size of the file like this
fileInfo.Length
For more info look at this msdn page.
Without interop and like the first comment, once the dialogue has been complete i.e. file/s have been selected this would give the size.
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (openFileDialog1.Multiselect)
{
long total = 0;
foreach (string s in openFileDialog1.FileNames)
total += new FileInfo(s).Length;
MessageBox.Show(total.ToString());
}
else
{
MessageBox.Show(new FileInfo(openFileDialog1.FileName).Length.ToString());
}
}
}
File size during dialogue I feel would need to use interop
Andrew
I think there is 3 way, creating your custom open dialog or setting by code the view as detail or asking the user to use detail view
If you mean when the dialog is running, I suspect you just change the file view to details. However if you mean programmatically I suspect that you'd have to hook a windows message when the file is selected.
Related
Using File.OpenDialog how can i make a copy of selected files to a certain (predeclared or even better from a string variable taken from textbox) location?
I assume i can firstly simply use the ofd method, but where to determine the location to copy?
InitializeComponent();
PopulateTreeView();
this.treeView1.NodeMouseClick +=
new TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseClick);
OpenFileDialog ofd1 = new OpenFileDialog();
and for the button:
private void button3_Click(object sender, EventArgs e)
{
if (ofd1.ShowDialog() == DialogResult.OK)
{ }
}
If I understood correctly, then once you select the file from open file dialog, you want to copy it to a certain location. Then you can use something like this code -
if (this.openFileDialog1.ShowDialog()== System.Windows.Forms.DialogResult.OK)
{
var fileName = this.openFileDialog1.FileName;
File.Copy(fileName, "DestinationFilePath");
}
Or in case of multiple selected file, something like this -
if (this.openFileDialog1.ShowDialog()== System.Windows.Forms.DialogResult.OK)
{
var fileNames = this.openFileDialog1.FileNames;
foreach (var fileName in fileNames)
{
File.Copy(fileName, "DestinationFilePath/" + fileName);
}
}
Check out the foreach loop in this for iterating through all of the files you selected using the OpenDialog.
I think this is what you're looking for in regards to actually copying the files. It takes a source directory and copies to the destination you provide.
i have a folder full of images etc and i want to add them to my gui inside a tab once the program is ran.
steps:
read contents inside folder
add images to tabcontrol and assign a number to them according to in what order they were added (1) for the first picture added (2) for second etc
the images need to be added in rows of 3 with differend x values for every 3 pictures each and 1 y value change for each row of 3
[] [] []
[] [] []
[] []
doesnt need to be divideable in 3 ^ this is fine
my issue is that i didnt even find a way to add images to a gui without using the designer and im fairly new to c# so this is a huge challange for me :(
in AHK i would just gui,add,picture but it doesnt work that way in c#
help or some form of tips/guidance is very appreciated
the reason the pictures need to "have a value" on them is that once they are clicked i know which image was clicked because they should all have their click event be sent to the same function that checks what number that was and changes the value of variables accordingly
thanks for the help SO C# is overwhelming
public static void ProcessDirectory(string targetDirectory)
{
Console.WriteLine("Processed folder '{0}'.", targetDirectory);
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
ProcessFile(fileName);
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
// Insert logic for processing found files here.
public static void ProcessFile(string path)
{
Console.WriteLine("Processed file '{0}'.", path);
if (!ImageExtensions.Contains(Path.GetExtension(path).ToUpperInvariant()))
{
Console.WriteLine("not image");
return;
}
FlowLayoutPanel flowLayoutPanel1 = new FlowLayoutPanel();
Image i = new Bitmap(path);
PictureBox p = new PictureBox();
p.Image = i;
p.Tag = "im1";
p.Click += OnImageClick; // this will let you have the same event for all of the pictures
flowLayoutPanel1.Controls.Add(p);
}
// this is what handles the clicks
private static void OnImageClick(object sender, EventArgs e)
{
MessageBox.Show("hey");
// I will leave this for you to implement... the 'sender' is the picturebox that was clicked.
// you can get it back to a PictureBox by casting, like (PictureBox)sender
// throw new NotImplementedException();
}
To add images, text, or anything else to a GUI programmatically in Winforms (which is sounds like you're using) you'll create an instance of something derived from Control and add it to the form's Controls ControlCollection. You can use a FLowLayoutPanel to give it a grid like view.
// get the list of paths to the files from your directory into an array
var fileList = Directory.GetFiles(#"C:\Images","*.jpg");
// create a flowlayout panel
FlowLayoutPanel f = new FlowLayoutPanel();
foreach (string path in fileList)
{
Image i = new Bitmap(path);
PictureBox p = new PictureBox();
p.Image = i;
p.Click += OnImageClick; // this will let you have the same event for all of the pictures
f.Controls.Add(p);
}
// add the panel to the form
this.Controls.Add(p);
// this is what handles the clicks
private void OnImageClick(object sender, EventArgs e)
{
// I will leave this for you to implement... the 'sender' is the picturebox that was clicked.
// you can get it back to a PictureBox by casting, like (PictureBox)sender
throw new NotImplementedException();
}
This implementation is quick and dirty: that is, it doesn't handle if the directory isn't found, if there aren't any files in there, etc). It should give you a good idea of where to go. I would recommend reading a lot more, getting a book about C# and walking through some examples/tutorials can be immensely helpful. You're right, C# can be overwhelming... that's why Google is your best friend! You don't need to immediately learn how to do everything; I find I learn well by choosing a small-in-scope project that I want to do and learning as I find things that I need.
This MSDN article talks about how to get all the filepaths of files in specific directory ("folder")
Their example:
// For Directory.GetFiles and Directory.GetDirectories
// For File.Exists, Directory.Exists
using System;
using System.IO;
using System.Collections;
public class RecursiveFileProcessor
{
public static void Main(string[] args)
{
foreach(string path in args)
{
if(File.Exists(path))
{
// This path is a file
ProcessFile(path);
}
else if(Directory.Exists(path))
{
// This path is a directory
ProcessDirectory(path);
}
else
{
Console.WriteLine("{0} is not a valid file or directory.", path);
}
}
}
// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)
ProcessFile(fileName);
// Recurse into subdirectories of this directory.
string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach(string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
// Insert logic for processing found files here.
public static void ProcessFile(string path)
{
Console.WriteLine("Processed file '{0}'.", path);
}
}
This article (also MSDN) talks about adding control dynamically at run time, here is their example code:
// C#
private void button1_Click(object sender, System.EventArgs e)
{
TextBox myText = new TextBox();
myText.Location = new Point(25,25);
this.Controls.Add (myText);
}
Finally this article (again MSDN) article talks about how to set an image from a file, here is their example code:
// C#
// You should replace the bolded image
// in the sample below with an icon of your own choosing.
// Note the escape character used (#) when specifying the path.
pictureBox1.Image = Image.FromFile
(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.MyPictures)
+ #"\Image.gif");
EDIT: In the comments it was asked how to wire up a control click event, since we are adding these controls programmatically we need to add the click event programmatically. For demo purposes assume there is a control with id Button1, to fire a function when it is clicked you would use code that goes something like this:
Button1.Click += new System.EventHandler(this.myEventHandler);
This will fire the function myEventHandler when Button1 is clicked
So thats a lot of code!
While it may not seem like it, if you look at each piece and consider how they all fit together, this should help you on the right path to (big hint), dynamically get a list of images, add an image control to your page, then set that image control to display a specific image, and finally wire up a click event on an image control
You can use Image.Tag property to add extra information to the image.
I created simple program for save/open practice. Made a setup and associated my program with my own datatype, called it .xxx (for practice).
I managed to Save and Open code and data from textbox but only from my program. Double click (or enter from windows-desktop) open up my WindowsForm as it is but there is an empty textbox. I want my saved file to be opened on double click in the same condition as when I open it from my program. How to set that up??
Here is the code of simple app (cant post images but it simple - got 1 label and 1 textbox with open and save buttons):
private void ButOpen_Click(object sender, EventArgs e)
{
textBox1.Text = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string data = Read(openFileDialog1.FileName);
textBox1.Text = data;
}
else
{//do nothing }
}
private string Read(string file)
{
StreamReader reader = new StreamReader(file);
string data = reader.ReadToEnd();
reader.Close();
return data;
}
private void ButSave_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Something|*.xxx";
DialogResult result = saveFileDialog1.ShowDialog();
string file = saveFileDialog1.FileName.ToString();
string data = textBox1.Text;
Save(file, data);
}
private void Save(string file, string data)
{
StreamWriter writer = new StreamWriter(file);
writer.Write(data);
writer.Close();
}
NOTE:
My similar question was marked as duplicate but it is not, and this question which was referenced as duplicate Opening a text file is passed as a command line parameter does not help me.It's not the same thing...
Just wanted to find out how to configure registry so windows understand and load data inside the file, or to file save data somehow so i can open it with double click.
So someone please help. If something is not clear I will give detailed information just ask on what point.
Thanks
MSDN has some information about this:
https://msdn.microsoft.com/en-us/library/bb166549.aspx
Basically you need to create an entry in the registry so that explorer.exe knows to launch your program when that file is activated (e.g. double-clicked).
Explorer will then pass the path to the file as an argument to your program.
I can't find a solution for this problem:
I write a program, which reads all file in a directory and puts them in a listbox.
When a user select a file from a listbox, the program reads the selected file and prints out some info...
The problem is that after the firs selection my program "stop working". He don't crash, but when I try to select another file he do nothing.
I figured out, that the problem is in:
private String porocilo(String s)
{
file = "/path to file/";
TextReader tr = new StreamReader(file); //<- problem here
//...
tr.close();
return someinfo;
}
//..
//Call function:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = porocilo(listBox1.SelectedItems[0].ToString());
}
After removing that (problem) line the program normally select files, but without this I can't read files and my program don't do anything.
Can someone tell me where I'm wrong?
Br, Wolfy
If the code you posted is really the code you are using (plus the missing semicolon), then the reason you are not seeing anything happening is because your code keeps opening and reading the same file, not the file the user selected. You are setting file to a constant path/filename and read from that, and you are not making use of the s parameter.
It looks like you have a hard-coded path in your porocilo method. That is, new StreamReader is taking as it's argument, file, not s.
So it will only ever open, one file, not the file you selected.
private String porocilo(String s)
{
//file = "/path to/file" // not sure what this is...???
TextReader tr = new StreamReader(s); //<- fix here
//...
tr.close();
return someinfo;
}
In your List box Selected index change method you need to assign the selected value as shown below
//Call function:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = porocilo(listBox1.SelectedItem.Text);
}
Also check your "porocilo" function it uses the parameter corectly
can any expert help me out to solve a problem of burning a dvd using c#.net as a front end??
i need to select files from the listview in winform and then on button click i need to burn those multiple files in the dvd..
the concept is to select the multiple files from listview then on button click it should make a folder in some desired drive.. and then it should burn that complete folder in the dvd..this whole process should be performed during a single button click....
is there any way out??
the code should be compatible to use in .net2008 and windowsXP are the given codes compatible??
im using the componenet to get the dll/class lib. from (msdn.microsoft.com/en-au/vcsharp/aa336741.aspx) but its giving me error message "there are no components in d:\filepath\burncomponent.dll to be placed on the toolbox
private void button1_Click(object sender, EventArgs e)
{
XPBurnCD cd = new XPBurnCD();
cd.BurnComplete += new NotifyCompletionStatus(BurnComplete);
MessageBox.Show(cd.BurnerDrive);
DirectoryInfo dir = new DirectoryInfo(_burnFolder);
foreach (FileInfo file in dir.GetFiles())
{
cd.AddFile(file.FullName, file.Name);
}
cd.RecordDisc(false, false);
}
private void BurnComplete(uint status)
{
MessageBox.Show("Finished writing files to disc");
}
private void button2_Click_1(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.ShowNewFolderButton = false;
fbd.Description = "Please select a folder";
fbd.RootFolder = System.Environment.SpecialFolder.DesktopDirectory;
if (fbd.ShowDialog() == DialogResult.OK)
{
_burnFolder = fbd.SelectedPath;
}
else
{
_burnFolder = string.Empty;
}
}
Check out http://msdn.microsoft.com/en-au/vcsharp/aa336741.aspx
One simple approach could be to use the command line tools dvdburn and cdburn, which are belonging to XP. For example take a look at this site.
Update
Yes, it is a console application, but you can start it within a .Net Application by using the Process class. And here you should especially take a deeper look into the StartInfo property and its members, cause here you can set the parameters or redirect the output into your program to get informations about what the program is doing.