Read Multiple Textfile upon Button Click and Display Content - c#

I initially have a Fileupload tool to upload a textfile, manipulate its content and display into a Listbox or Textbox. The limitation however is Fileupload only supports single uploading, at least to the version of .Net Framework I am using.
What I intend to do is just use a button control and remove the Fileupload. Upon Button click I need to read the textfiles inside a designated folder path and display first the contents inside a multiple lined textbox. (not just the file name) This is my intially written codes, and it is not working.
protected void btnGetFiles_Click(object sender, EventArgs e)
{
string content = string.Empty;
DirectoryInfo dinfo = new DirectoryInfo(#"C:\samplePath");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
//ListBox1.Items.Add(file.Name);
content += content;
}
txtContent.Text = content;
}

Since your's is web based application you can't access physical paths like c:\\.. you should use Server.MapPath anyway(As per the comment, you don't need to get the file with Server.MapPath). Then for getting the content you can try something like the following:
protected void btnGetFiles_Click(object sender, EventArgs e)
{
try
{
StringBuilder content = new StringBuilder();
if (Directory.Exists(#"C:\samplePath"))
{
// Execute this if the directory exists
foreach (string file in Directory.GetFiles(#"C:\samplePath","*.txt"))
{
// Iterates through the files of type txt in the directories
content.Append(File.ReadAllText(file)); // gives you the conent
}
txtContent.Text = content.ToString();
}
}
catch
{
txtContent.Text = "Something went wrong";
}
}

you wrote content += content;, that is the problem. change it to content += file.Name;, it will work.

Related

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 image from folder to dropdown list

I want to add images from folder and list it in dropdown . Like my application has folder name flags containing all the flags images and their country name. how do I add them to dropdown .
Try using the System.IO.Directory.GetFiles and System.IO.Path.GetFileName
http://msdn.microsoft.com/en-us/library/system.io.directory.getfiles(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.io.path.getfilename(v=vs.110).aspx
Something like (haven't tried it)
// Process the list of files found in the directory.
string [] files = Directory.GetFiles(yourDirectory);
foreach(string file in files) {
string language = Path.GetFileName(file);
ddlFlags.Items.Add(new ListItem(language, file));
}
Next time, improve your question by describing what you have tried so far, then it would be easier to help you.
You should include the System.IO namespace and add an ImageList to your form. Set its ImageSize to a nice size for you images.
Then use the code below to do the rest! It loads all files in a folder into both an ImageList and into the Items of a ComboBox. Note that it loads not the filenames but FileInfo objects, so that it can easily display the names without the path. Also note that to display images in a CombBox it has to be owner-drawn, which, as you can see it pretty straight-forward..
Here is the code to use & study:
using System.IO;
//..
// load whereever you like
// e.g. in the From.Load event or after InitializeComponent();
var images = Directory.GetFiles(yourImageFolder, "*.jpg");
foreach (string file in images)
{
imageList1.Images.Add(file, new Bitmap(file));
comboBox1.Items.Add(new FileInfo(file));
}
comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
comboBox1.DrawItem += comboBox1_DrawItem;
comboBox1.ItemHeight = imageList1.ImageSize.Height;
void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
FileInfo FI = (FileInfo)comboBox1.Items[e.Index];
e.Graphics.DrawImage(imageList1.Images[FI.FullName], e.Bounds.Location);
e.Graphics.DrawString(FI.Name, Font, Brushes.Black,
e.Bounds.Left + imageList1.ImageSize.Height + 3, e.Bounds.Top + 4);
}

C# Save all items in a ListBox to text file

Recently I've been quite enjoying C# and I'm just testing with it but there seems to be one part I don't get.
Basically I want it so that when I click the SAVE button must save all the items in the listbox to a text file. At the moment all it comes up with in the file is System.Windows.Forms.ListBox+ObjectCollection.
Here's what I've got so far. With the SaveFile.WriteLine(listBox1.Items); part I've tried putting many different methods in and I can't seem to figure it out. Also take in mind that in the end product of my program I would like it to read back to that to that text file and output what's in the text file to the listbox, if this isn't possible then my bad, I am new to C# after all ;)
private void btn_Save_Click(object sender, EventArgs e)
{
const string sPath = "save.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
SaveFile.WriteLine(listBox1.Items);
SaveFile.ToString();
SaveFile.Close();
MessageBox.Show("Programs saved!");
}
From your code
SaveFile.WriteLine(listBox1.Items);
your program actually does this:
SaveFile.WriteLine(listBox1.Items.ToString());
The .ToString() method of the Items collection returns the type name of the collection (System.Windows.Forms.ListBox+ObjectCollection) as this is the default .ToString() behavior if the method is not overridden.
In order to save the data in a meaningful way, you need to loop trough each item and write it the way you need. Here is an example code, I am assuming your items have the appropriate .ToString() implementation:
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
foreach(var item in listBox1.Items)
{
SaveFile.WriteLine(item.ToString());
}
Items is a collection, you should iterate through all your items to save them
private void btn_Save_Click(object sender, EventArgs e)
{
const string sPath = "save.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
foreach (var item in listBox1.Items)
{
SaveFile.WriteLine(item);
}
SaveFile.Close();
MessageBox.Show("Programs saved!");
}
There is one line solution to the problem.
System.IO.File.WriteAllLines(path, Listbox.Items.Cast<string>().ToArray());
put your file path+name and Listbox name in above code.
Example:
in Example below path and name of the file is D:\sku3.txt and list box name is lb
System.IO.File.WriteAllLines(#"D:\sku3.txt", lb.Items.Cast<string>().ToArray());

Dynamically adding LinkLabels to a TableLayoutPanel

I've been having a problem with the following code:
namespace Viewer
{
public partial class Form1 : Form
{
int count = 0;
LinkLabel[] linkLabel = new LinkLabel[200];
string filename;
string extension;
string filepath;
private void btnLoad_Click(object sender, EventArgs e)
{
// Creates a Directory for the Movies Folder
DirectoryInfo myDirectory = new DirectoryInfo(#"C:\Users\User\Movies");
// Creates a list of "File info" objects
List<FileInfo> ls = new List<FileInfo>();
// Adds filetypes to the list
ls.AddRange(myDirectory.GetFiles("*.mp4"));
ls.AddRange(myDirectory.GetFiles("*.avi"));
// Orders the list by Name
List<FileInfo> orderedList = ls.OrderBy(x => x.Name).ToList();
// Loop through file list to act on each item
foreach (FileInfo filFile in orderedList)
{
// Creates a new link label
linkLabel[count] = new LinkLabel();
// Alters name info for display and file calling
filepath = filFile.FullName;
extension = filFile.Extension;
filename = filFile.Name.Remove(filFile.Name.Length - extension.Length);
// Write to the textbox for functional display
textBox1.AppendText(filename + "\r\n");
// Alters link label settings
linkLabel[count].Text = filename;
linkLabel[count].Links.Add(0, linkLabel[count].Text.ToString().Length, filepath);
linkLabel[count].LinkClicked += new LinkLabelLinkClickedEventHandler(LinkedLabelClicked);
// Adds link label to table display
tblDisplay.Controls.Add(linkLabel[count]);
// Indexes count up for arrays
count = count + 1;
}
}
private void LinkedLabelClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start(filepath);
}
}
}
My goal is to generate a table of links to all of the media files that I add at launch, and have the links open the files in their respective players.
As of right now, it generates all of the links properly, but whenever I click on any of them, it launches the last item in the list.
For example, if the list contains "300", "Gladiator", and "Top Gun", no matter which link I click, it opens "Top Gun".
I assume that this has to do with it calling the variable "filepath" in the click event, which is left in it's final state. However, I'm not exactly clear on how to create a static link value or action on each individual link, as all of the answers I've researched are in regards to single linklabel situations, not dynamic set-ups.
Any help/advice would be appreciated!
Try as below:
In foreach loop add one line more like:
linkLabel[count].Tag = filepath;
then in click event get this path as blow,
private void LinkedLabelClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string filepath = ((LinkLabel)sender).Tag.tostring();
System.Diagnostics.Process.Start(filepath);
}

Getting the path of a file using fileupload control

I am using a fileupload control to display the contents of a text file in a textbox..if i use this
<asp:FileUpload ID="txtBoxInput" runat="server" Text="Browse" />
string FilePath = txtBoxInput.PostedFile.FileName;
it will get only the file name like bala.txt.i need like this D:\New Folder\bala.txt
Instead of fileupload control i have used textbox to get the path like this D:\New Folder\bala.txt
<asp:TextBox ID="txtBoxInput" runat="server" Width="451px"></asp:TextBox>
string FilePath = txtBoxInput.Text;
But i need browse button instead of textbox to get the path...Any Suggestion??
EDIT:My button click event
protected void buttonDisplay_Click(object sender, EventArgs e)
{
string FilePath = txtBoxInput.PostedFile.FileName;
if (File.Exists(FilePath))
{
StreamReader testTxt = new StreamReader(FilePath);
string allRead = testTxt.ReadToEnd();
testTxt.Close();
}
}
You can get the file name and path from FileUpload control only when you are in debug mode but when you deployed your app. in server then you cant because that is your client address which you are trying to access by server side code.
protected void Button1_Click(object sender, EventArgs e)
{
string filePath,fileName;
if (FileUpload1.PostedFile != null)
{
filePath = FileUpload1.PostedFile.FileName; // file name with path.
fileName = FileUpload1.FileName;// Only file name.
}
}
If you really want to change properties or rename client file then you can save file on server on temp folder then you can do all thing which you want.
http://forums.asp.net/t/1077850.aspx

Categories

Resources