From below given foreach loop I'm getting all the file names in a folder. I want to know how to put all the file names in text box. According to below code only the last file name appear in textbox.
private void btnGetFileNames_Click(object sender, EventArgs e)
{
DirectoryInfo dinf = new DirectoryInfo(tbxFileLocation.Text);
foreach (FileInfo Fi in dinf.GetFiles())
{
tbxFileList.Text=Fi.ToString();
}
}
Use a StringBuilder and append the filenames to it, Display finally
StringBuilder filenames = new StringBuilder();
foreach (FileInfo Fi in dinf.GetFiles())
{
filenames.Append(Fi.ToString());
filenames.Append(",");
}
tbxFileList.Text=filenames.ToString();
Try this :
private void btnGetFileNames_Click(object sender, EventArgs e)
{
DirectoryInfo dinf = new DirectoryInfo(tbxFileLocation.Text);
foreach (FileInfo Fi in dinf.GetFiles())
{
tbxFileList.Text+=Fi.ToString() + Environment.NewLine;
}
}
Related
I have all the dirctories (2014, 2012), the files of each selected folder (.pdf) in the listbox 2
I get the dirctories by this code
if (FBD.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Clear();
DirectoryInfo[] diri_info = newDirectoryInfo(FBD.SelectedPath).GetDirectories();
foreach (DirectoryInfo diri in diri_info)
{
listBox1.Items.Add(diri);
}
and i get the files by this code
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex >= 0)
{
DirectoryInfo dirictory_choisis = (DirectoryInfo)listBox1.SelectedItem;
FileInfo[] files = dirictory_choisis.GetFiles();
listBox2.Items.Clear();
foreach (FileInfo file in files)
{
listBox2.Items.Add(file);
}
}
else
{
MessageBox.Show("selectioner un dossier");
}
}
Now how I can open the selected file (.pdf) ?
i use this code but dosn't work ( throw an exception file dosn't found)
private void listBox2_Click(object sender, EventArgs e)
{
FileInfo file = (FileInfo) listBox2.SelectedItem;
Process.Start(file.Name);
}
There is a syntax error in your code: "newDirectoryInfo"
By the way, file.Name only returns the name (not including path). You should replace that line with:
Process.Start(file.FullName);
So the listBox2_Click should be like this:
private void listBox2_Click(object sender, EventArgs e)
{
FileInfo file = (FileInfo)listBox2.SelectedItem;
Process.Start(file.FullName);
}
I have this in my designer:
On the right is the files in a listView1.
On the left is the directory main directory of this files treeView1.
I have this code in menu strip item clicked event :
void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Text == "Upload")
{
List<String> selected = new List<String>();
foreach (ListViewItem lvi in listView1.SelectedItems)
{
selected.Add(lvi.Text);
}
AllFiles = selected.ToArray();
Bgw.RunWorkerAsync();
}
}
The problem is that the file/s in AllFiles array are only the filenames for example: bootmgr or install.exe
But i need that in the All Files each file will have also it's full path for example:
c:\bootmgr or c:\install.exe or c:\test\test\example.txt
How can i add to AllFiles also the paths ?
I tried now:
void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Text == "Upload")
{
List<String> selected = new List<String>();
string dir = treeView1.SelectedNode.FullPath;
foreach (ListViewItem lvi in listView1.SelectedItems)
{
string g = Path.Combine(dir, lvi.Text);
selected.Add(g);
}
AllFiles = selected.ToArray();
Bgw.RunWorkerAsync();
}
}
And in form1:
private void FtpProgress_DoWork(object sender, DoWorkEventArgs e)
{
f = new FtpSettings();
f.Host = "ftP://ftp.newsxpressmedia.com";
f.Username = "...";
f.Password = "...";
files = TV_LV_Basic.ExplorerTree.AllFiles;
StringArrayUploadFiles(sender, e);
}
AllFiles contain the files and paths for example C:\test.txt
Then :
private void StringArrayUploadFiles(object sender, DoWorkEventArgs e)
{
try
{
foreach (string txf in files)
{
string fn = txf;
BackgroundWorker bw = sender as BackgroundWorker;
if (f.TargetFolder != "" && f.TargetFolder != null)
{
createDirectory(f.TargetFolder);
}
else
{
f.TargetFolder = Path.GetDirectoryName(txf);
//createDirectory(f.TargetFolder);
}
string UploadPath = String.Format("{0}/{1}{2}", f.Host, f.TargetFolder == "" ? "" : f.TargetFolder + "/", Path.GetFileName(fn));
Now in txf for example i have C:test.txt
Then in f.TargetFolder i have: C:
Then in UploadPath i have: ftp://ftp.newsxpressmedia.com/C:/eula.1031.txt
But instead C: i need it to look like: ftp://ftp.newsxpressmedia.com/C/eula.1031.txt
And there are sub directories for example then: ftp://ftp.newsxpressmedia.com/C/Sub/Dir/eula.1031.txt
In the menuStrip1_ItemClicked event when i select a file for example test.txt already in this event i did a mess.
FileInfo fi = new FileInfo("temp.txt");
Determine the full path of the file just created.
DirectoryInfo di = fi.Directory;
Figure out what other entries are in that directory.
FileSystemInfo[] fsi = di.GetFileSystemInfos();
to display directoryinfo fullname in console
Console.WriteLine("The directory '{0}' contains the following files and directories:", di.FullName);
Print the names of all the files and subdirectories of that directory.
foreach (FileSystemInfo info in fsi)
Console.WriteLine(info.Name);
Here
My code for opening word file from a directory on local machine on a button click event:
`string path = #"C:\Users\Ansar\Documents\Visual Studio 2010\Projects\GoodLifeTemplate\GoodLifeTemplate\Reports\IT";
List<string> AllFiles = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ParsePath();
}
}
void ParsePath()
{
string[] SubDirs = Directory.GetDirectories(path);
AllFiles.AddRange(SubDirs);
AllFiles.AddRange(Directory.GetFiles(path));
int i = 0;
foreach (string subdir in SubDirs)
{
ListBox1.Items.Add(SubDirs[i].Substring(path.Length + 1, subdir.Length - path.Length - 1).ToString());
i++;
}
DirectoryInfo d = new DirectoryInfo(path);
FileInfo[] Files = d.GetFiles("*.doc")
ListBox1.Items.Clear();
foreach (FileInfo file in Files)
{
ListBox1.Items.Add(file.ToString());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ListBox1.SelectedItem != null)
{
Microsoft.Office.Interop.Word.Application ap = new Microsoft.Office.Interop.Word.Application();
Document document = ap.Documents.Open(path + "\\" + ListBox1.SelectedItem.Text);
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "error", "Please select file;", true);
}
`
This is showing all word files list in the listbox as my requirement is but also the previously opened temporary word files that is (~$nameoffile.docx) I dont want to display this (~$nameoffile.docx) in the list of list box.
The files ~$[something].docx are hidden files. What I would recommend you to do is make sure you filter them out like:
System.IO.DirectoryInfo dirInf = new System.IO.DirectoryInfo(#"C:\myDir\Documents");
var files = dirInf.GetFiles("*.doc").Where(f => (f.Attributes & System.IO.FileAttributes.Hidden) != System.IO.FileAttributes.Hidden).ToArray();
The search pattern of dirInf.GetFiles works in the same way the windows does.
This is a Lambda Expression:
.Where(f => (f.Attributes & System.IO.FileAttributes.Hidden) != System.IO.FileAttributes.Hidden)
And this is a bitwise comparison:
(f.Attributes & System.IO.FileAttributes.Hidden) != System.IO.FileAttributes.Hidden
I can reach with foreach to directory but, because of working like stack, I only reach last picture in the directory. I have lot of image that starting 1.jpg until 100.
namespace deneme_readimg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo("C:\\DENEME");
foreach (FileInfo file in dir.GetFiles())
textBox1.Text = file.Name;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
I am unsure what you are asking or what you are trying to achieve, but if you want to see all of the names, you could change the foreach loop into:
foreach (FileInfo file in dir.GetFiles())
textBox1.Text = textBox1.Text + " " + file.Name;
As suggested by #LarsKristensen I'm posting my comment as an answer.
I would use the AppendText method, unless your requirement is to add to the text box on every click I would first make a call to Clear.
namespace deneme_readimg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo("C:\\DENEME");
// Clear the contents first
textBox1.Clear();
foreach (FileInfo file in dir.GetFiles())
{
// Append each item
textBox1.AppendText(file.Name);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
Just collect all the data you need to output in StringBuilder;
when ready publish it:
DirectoryInfo dir = new DirectoryInfo("C:\\DENEME");
// Let's collect all the file names in a StringBuilder
// and only then assign them to the textBox.
StringBuilder Sb = new StringBuilder();
foreach (FileInfo file in dir.GetFiles()) {
if (Sb.Length > 0)
Sb.Append(" "); // <- or Sb.AppendLine(); if you want each file printed on a separate line
Sb.Append(file.Name);
}
// One assignment only; it prevents you from flood of "textBox1_TextChanged" calls
textBox1.Text = Sb.ToString();
for displaying just File name. Use a multiline textbox
StringBuilder sb = new StringBuilder();
foreach (FileInfo file in dir.GetFiles())
sb.Append(file.Name + Environment.NewLine);
textBox1.Text =sb.ToString().Trim();
if you want to show images then you need to use some datacontainer like ListBox or DataGridView and add row for each image.
I have a Repeater that takes all my images in a folder and display it. But what code changes must I make to only allow lets say Image1.jpg and Image2.jpg to be displayed in my repeater. I don"t want the repeater to display ALL the images in my folder.
My Repeater
<asp:Repeater ID="repImages" runat="server" OnItemDataBound="repImages_ItemDataBound">
<HeaderTemplate><p></HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="hlWhat" runat="server" rel="imagebox-bw">
<asp:Image ID="imgTheImage" runat="server" />
</asp:HyperLink>
</ItemTemplate>
<FooterTemplate></p></FooterTemplate>
</asp:Repeater>
My Code behind - PAGE LOAD
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sBasePath = System.Web.HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"];
if ( sBasePath.EndsWith("\\"))
sBasePath = sBasePath.Substring(0,sBasePath.Length-1);
sBasePath = sBasePath + "\\" + "pics";
System.Collections.Generic.List<string> oList = new System.Collections.Generic.List<string>();
foreach (string s in System.IO.Directory.GetFiles(sBasePath, "*.*"))
{
//We could do some filtering for example only adding .jpg or something
oList.Add( System.IO.Path.GetFileName( s ));
}
repImages.DataSource = oList;
repImages.DataBind();
}
}
My Code behind - Repeater's ItemDataBound event code
protected void repImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem ||
e.Item.ItemType == ListItemType.Item)
{
string sFile = e.Item.DataItem as string;
//Create the thumblink
HyperLink hlWhat = e.Item.FindControl("hlWhat") as HyperLink;
hlWhat.NavigateUrl = ResolveUrl("~/pics/" + sFile );
hlWhat.ToolTip = System.IO.Path.GetFileNameWithoutExtension(sFile);
hlWhat.Attributes["rel"] = "imagebox-bw";
Image oImg = e.Item.FindControl("imgTheImage") as Image;
oImg.ImageUrl = ResolveUrl("~/createthumb.ashx?gu=/pics/" + sFile + "&xmax=100&ymax=100" );
}
}
ANSWER:
My updated Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sBasePath = System.Web.HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"];
if ( sBasePath.EndsWith("\\"))
sBasePath = sBasePath.Substring(0,sBasePath.Length-1);
sBasePath = sBasePath + "\\" + "pics";
System.Collections.Generic.List<string> oList = new System.Collections.Generic.List<string>();
string[] extensions = { "*.jpg", "*.png" };
List<string> files = new List<string>();
foreach (string filter in extensions)
{
files.AddRange(System.IO.Directory.GetFiles(sBasePath, filter));
oList.Add(System.IO.Path.GetFileName(filter));
}
repImages.DataSource = oList;
repImages.DataBind();
}
What format are the image names that you want to display? If you know that you can construct a filter to use when listing the contents of the directory:
string[] files = Directory.GetFiles(folder, "*1.jpg");
Will list all the jpg files that end in "1"
EDIT:
Instead of having:
foreach (string s in System.IO.Directory.GetFiles(sBasePath, "*.*"))
{
//We could do some filtering for example only adding .jpg or something
oList.Add( System.IO.Path.GetFileName( s ));
}
You'd have:
string[] files = System.IO.Directory.GetFiles(sBasePath, "*.jpg")
foreach (string s in files)
{
oList.Add( System.IO.Path.GetFileName( s ));
}
EDIT 2:
I've done a quick search and it looks like Get Files won't take multiple extensions, so you'll have to search for each type of extension separately:
string[] extensions = {"*.jpg" , "*.png" };
List<string> files = new List<string>();
foreach(string filter in extensions)
{
files.AddRange(System.IO.Directory.GetFiles(path, filter));
}
foreach (string s in files)
{
oList.Add( System.IO.Path.GetFileName( s ));
}
Easiest way to is load them all into a List<> and then use Linq to filter out the ones you want.
VS2005
public class GetFiles
{
public static void Main(string[] args)
{
FileInfo[] files =
new DirectoryInfo(#"D:\downloads\_Installs").GetFiles();
ArrayList exefiles = new ArrayList();
foreach (FileInfo f in files)
{
if (f.Extension == ".exe") // or whatever matching you want to do.
{
exefiles.Add(f);
}
}
foreach (FileInfo f in exefiles)
{
Console.WriteLine(f.FullName);
}
Console.ReadKey();
}
}
VS2008
public class GetFiles
{
public static void Main(string[] args)
{
FileInfo[] files =
new DirectoryInfo(#"D:\downloads\_Installs").GetFiles();
var exefiles = from FileInfo f in files
where f.Extension == ".exe"
select f;
foreach (FileInfo f in exefiles)
{
Console.WriteLine(f.FullName);
}
Console.ReadKey();
}
}
What you will need to do is filter out all the images you do not wish to display from your list before you bind it to your repeater control.