How do I use the variable of the selected folder? - c#

When i select a folder manually, through FolderBrowserDialog, my need to substitute the path to the code below.
Where "%ProgramFiles (x86)%\MyApp" must be replaced with the variable of the selected folder + file name.
As a result, when selecting a folder, the file size "testFile.txt" in "label1" should be displayed (there will be two or more such files).
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
DialogResult result = folderBrowser.ShowDialog();
if (result == DialogResult.OK)
{
// Determine the size of the file in KB (dividing the number of bytes by 1024)
FileInfo fs1 = new FileInfo(Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%\\MyApp\\testFile.txt"));
long FileSize1 = fs1.Length / 1024;
label1.Text = "testFile.txt (" + Convert.ToString(FileSize1) + " KB)";
if (FileSize1 > 180 & FileSize1 < 186) // If the file is larger and smaller than the specified sizes
{
label1.ForeColor = Color.Green;
}
else
{
label1.ForeColor = Color.Red;
}
}
}
Decision, edit:
FileInfo fs1 = new FileInfo(folderBrowser.SelectedPath + "\\testFile.txt");
or
FileInfo fs1 = new FileInfo(Path.Combine(folderBrowser.SelectedPath, "testFile.txt"));

The official documentation has an item dedicated specifically to this: How to: Choose Folders with the Windows Forms FolderBrowserDialog Component
To choose folders with the FolderBrowserDialog component
In a procedure, check the FolderBrowserDialog component's DialogResult property to see how the dialog box was closed and get the
value of the FolderBrowserDialog component's SelectedPath property.
If you need to set the top-most folder that will appear within the tree view of the dialog box, set the RootFolder property, which takes
a member of the Environment.SpecialFolder enumeration.
Additionally, you can set the Description property, which specifies the text string that appears at the top of the
folder-browser tree view.
In the example below, the FolderBrowserDialog component is used to
select a folder, similar to when you create a project in Visual Studio
and are prompted to select a folder to save it in. In this example,
the folder name is then displayed in a TextBox control on the form. It
is a good idea to place the location in an editable area, such as a
TextBox control, so that users may edit their selection in case of
error or other issues. This example assumes a form with a
FolderBrowserDialog component and a TextBox control.
public void ChooseFolder()
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
}
}
According to that example, you can get a string to the chosen folder using folderBrowser.SelectedPath.

Related

Saving File with selectable extensions

So I made code again about saving files (you can select file name)
here:
private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(fastColoredTextBox1.Text);
}
}
}
the problem is I want to have 2 selectable extensions:
-.txt
-.md
because the code I wrote can save to any type of file(and if you didn't put anything I will save as . FILE) and I just want only 1 save file type.
Save dialog
You need to set the dialog's Filter property according to the pattern:
Text to show|Filter to apply|Text to show 2|Filter to apply 2|...
For example in your case, where you seem to be saying you want the save dialog to have a combo dropdown containing two things, one being Text and the other being Markdown, your Filter has 4 things:
.Filter = "Text files|*.txt|Markdown files|*.md";
It is typical to put the filter you will apply into the text you will show too, so the user can see what you mean by e.g. "Text files" but I've left that out for clarity.
For example you might choose to make it say Text files(*.txt)|*.txt - the text in the parentheses has no bearing on the way the filter works, it's literally just shown to the user, but it tells them "files with a .txt extension"
Footnote, you may have to add some code that detects the extension from the FileName if you're saving different content per what the user chose e.g.:
var t = Path.GetExtension(saveFileDialog.FileName);
if(t.Equals(".md", StringComparison.OrdinalIgnoreCase))
//save markdown
else
//save txt
You can just use the filter of your dialog to set the allowed extensions:
// Filter by allowed extensions
saveFileDialog1.Filter = "Allowed extensions|*.txt;*.md";

How Do I use Drag And Drop To Export A File (C#)

I am currently using a file dialog to export a file, but I was wondering how I could export my file using drag and drop. I couldn't figure out how to get the file path of where the item is being dropped. Here is the code that I used for open file dialogue in case its required.
if (this.listView1.SelectedItems.Count > 0)
{
ListViewItem item = this.listView1.SelectedItems[0];
string text = this.faderLabel8.Text;
if (!text.EndsWith(#"\"))
{
text = text + #"\";
}
using (SaveFileDialog dialog = new SaveFileDialog())
{
if (dialog.ShowDialog() == DialogResult.OK)
{
Jtag.ReceiveFile(item.SubItems[0].Text, text + item.SubItems[0].Text);
}
}
}
You don't need the path of where the file is being dropped. Instead you need to create a temporary file.
Save file to a temporary folder
Initiate drag on an event/command, such as mouse down, in the following way:
//(This example is uses WPF/System.Windows.DragDrop)
//Create temporary file
string fileName = "DragDropSample.txt";
var tempPath = System.IO.Path.GetTempPath();
var tempFilePath = System.IO.Path.Combine(tempPath, fileName);
System.IO.File.WriteAllText(tempFilePath, "Testing drag and drop");
//Create DataObject to drag
DataObject dragData = new DataObject();
dragData.SetData(DataFormats.FileDrop, new string[] { tempFilePath });
//Initiate drag/drop
DragDrop.DoDragDrop(dragSourceElement, dragData, DragDropEffects.Move);
For WinForms example and more details see:
Implement file dragging to the desktop from a .net winforms application?
If you want it to be useful through "drag and drop" you would require some sort of graphical interface that displays the files in a container where they are and then another container to where you want to move them. When you highlight an item with your mouse you add them to your itemList and when your drop them you copy them. Just make sure the List is emptied once in case you remove the highlight.

How do I Open Labels/Buttons with C# code?

Take a look on the code ,i hope you will understand what I'm trying to do:
private void btnOpen_Click(object sender, EventArgs e)
{
string[] Folders = Directory.GetDirectories(txtFolder.Text);
string foldername;
int count=0;
foreach (string f in Folders)
{
foldername = Path.GetDirectoryName(f);
Label newlabe = new Label();
newlabe.Location = new Point(12, 58);
newlabe.Text = foldername;
count++;
}
}
as you can see i insert a Directory Path into text box , then I opened an array which contains the sub Directories,the next step is to open labels which contains the sub directories names from the directory i insert to the text box, that's not working , what should i do ?
Use some kind of container and stack/add the labels into it. You don't need to assign a location to the label, as the container (depending on the container layout algorithm) will layout them for you.
I dont know whether you use WinForms or WPF or something else, so I will not write any sample code.
But here is some pseudocode:
create a container and add it to the form
for each folder
create a label for the folder
add the label to the container
by the way, have you tried a TreeView control?

adding files to listview in C#

I have a Listview and an "ADD" button,when I click on ADD i should be able to browse the files in computer, select files and when click OK or the Open, the file list should be added in the listview...how to do that...is listview correct or any other alternative...?
ListView should be fine for file listing. Just be aware that longer file paths are difficult to see (have to horizontally scroll which is bad!) if you are gonna just add the full path to list. You can toy with the idea of other representation like:
File.Txt (C:\Users\Me\Documents)
C:\Users\..\File.Txt
etc
As far as doing it using code is concerned, you will need to use OpenFileDialog control to let user choose the files.
var ofd = new OpenFileDialog ();
//add extension filter etc
ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
if(ofd.ShowDialog() == DialogResult.OK)
{
foreach (var f in openFileDialog1.FileNames)
{
//Transform the list to a better presentation if needed
//Below code just adds the full path to list
listView1.Items.Add (f);
//Or use below code to just add file names
//listView1.Items.Add (Path.GetFileName (f));
}
}
If you want to do this in the designer, you can take the following steps to add the images to the ListView control:
Switch to the designer, click on the ImageList component on the Component Tray, there will be a smart tag appear on the top-right corner of the ImageList.
Click the smart tag, and click "Choose Images" on the pane.
On the pop-up Image Collection Editor dialog, choose the images from the folder your want.
Click OK to finish adding images to the ImageList.
Click the ListView on the form, there will be a smart tag appear on the top-right corner.
Click the smart tag, you will find there're three ComboBoxes there, choose a ImageList from the list as you want.
Click the "Add items" option on the smart tag, a ListViewItem Collection Editor will appear, you can add items to the ListView, it's important here to set the ImageIndex or ImageKey property, or the image won't appear.
Click OK to finish item editing, now you'll find the images are displayed on the ListView.
If you want to add the images to the ListView by code, you can do something like this
give the following code in addButton_click
var fdlg = new OpenFileDialog();
fdlg.Multiselect = true;
fdlg.Title = "Select a file to add... ";
fdlg.InitialDirectory = "C:\\";
fdlg.Filter = "All files|*.*";
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
foreach (var files in fdlg.FileNames)
{
try
{
this.imageList1.Images.Add(Image.FromFile(files));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
this.listView1.View = View.LargeIcon;
this.imageList1.ImageSize = new Size(32, 32);
this.listView1.LargeImageList = this.imageList1;
//or
//this.listView1.View = View.SmallIcon;
//this.listView1.SmallImageList = this.imageList1;
for (int j = 0; j < this.imageList1.Images.Count; j++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
this.listView1.Items.Add(item);
}
}

User navigates to folder, I save that folder location to a string

How can I do this?
I want a user to click a button and then a small window pops up and lets me end-user navigate to X folder. Then I need to save the location of the folder to a string variable.
Any help, wise sages of StackOverflow?
using (FolderBrowserDialog dlg = new FolderBrowserDialog())
{
if (dlg.ShowDialog(this) == DialogResult.OK)
{
string s = dlg.SelectedPath;
}
}
(remove this if you aren't already in a winform)
If you're using Winforms, you can use a FolderBrowserDialog control. The path the user selects will be in the SelectedPath property.
string path = null;
FolderBrowserDialog dlg = new ();
if (dlg.ShowDialog() == DialogResult.OK)
{
path = dlg.SelectedPath;
}

Categories

Resources