I seek for solution which I need to search image at textbox.
When value in TextBox same with image name, the picturebox will display that image. Because I have many picture in 1 folder. Can anyone help me pleaseee? Here is my current code:
if (textBoxEmplNo.Text == "TR0319")
{
pictureBox1.Image = Image.FromFile(#"C:\Users\may\Documents\Visual Studio 2013\WebSites\EV\photo\tr0319.jpg");
}
Are you looking for something like this?
string imgFilePath = #"C:\Users\may\Documents\Visual Studio 2013\WebSites\EV\photo\" + textBoxEmplNo.Text + ".jpg"
if(File.Exists(imgFilePath))
{
pictureBox1.Image = Image.FromFile(imgFilePath);
}
else
{
// Display message that No such image found
}
Here's a variation that has a couple of advantages thay may or may not be beneficial to you:
var folderPath = #"C:\Users\may\Documents\Visual Studio 2013\WebSites\EV\photo";
var filePaths = Directory.GetFiles(folderPath);
var filePath = filePaths.FirstOrDefault(s => Path.GetFileNameWithoutExtension(s).Equals(textBox1.Text, StringComparison.CurrentCultureIgnoreCase));
if (filePath != null)
{
pictureBox1.ImageLocation = filePath;
}
That allows your image files to have any extension and it also won't lock the file when it opens one.
Related
For my project I'm setting up a page where you can change your profile and upload an image. I've got all of that to work but now I want to make my image unique by matching the file name with the Username (which already is unique)
but I couldn't find a good guide anywhere on google.
Here is my code:
{
if (PfFoto != null)
{
string pic = System.IO.Path.GetFileName(PfFoto.FileName);
string path = System.IO.Path.Combine(Server.MapPath("/images/PFfotos"), pic);
PfFoto.SaveAs(path);
return RedirectToAction("Index");
}
}
My username is stored in changePF.Name
and the file name is stored in pic
so does anyone know how to do this?
Simply change FileName before SaveAs like :
if (PfFoto != null)
{
string path = System.IO.Path.Combine(Server.MapPath("/images/PFfotos"), changePF.Name);
PfFoto.SaveAs(path);
return RedirectToAction("Index");
}
If you want your file name to be same as your user name (without the extension part matching), You may use the Path.GetExtension method to get the file extension(ex : .jpg or .png) and concatenate that with your unique username.
if (PfFoto != null)
{
var newFileName = changePF.Name + Path.GetExtension(PfFoto.FileName);
var path = System.IO.Path.Combine(Server.MapPath("/images/PFfotos"), newFileName);
PfFoto.SaveAs(path);
}
I'm writing a simple WinForms application which I will use prior to when I edit my video footage in order to know the total length of all the video files when combined and "edited".
So ideally, I load them up then get the duration of each video and tally them up.
However I get stuck in terms of which collection class to use since I am using an external library IWMPMedia in addition to WindowsMediaPlayer to get the filenames and duration.
When I use a string array to get the filename, I get the whole path, which is something I don't want. Please see the following code snippet:
using WMPLib;
public partial class frmBacklinkMediaSerializer : Form
{
WindowsMediaPlayer wmp;
IWMPMedia mediainfo;
Double Duration(String file)
{
wmp = new WindowsMediaPlayer();
mediainfo = wmp.newMedia(file);
return mediainfo.duration;
}
void callDialogBox()
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Filter = "MP4 Videos (*.mp4)|*.mp4";
theDialog.FilterIndex = 0;
theDialog.Multiselect = true;
DialogResult result = theDialog.ShowDialog();
string[] selected = theDialog.FileNames;
string strFilename = theDialog.FileName;
if (result == DialogResult.OK)
{
FileInfo oFileInfo = new FileInfo(strFilename);
string temp = Duration(strFilename).ToString();
TimeSpan conversion =
TimeSpan.FromSeconds(Duration(strFilename));
if (strFilename != null || strFilename.Length != 0)
{
MessageBox.Show("My file names are below: " + "\n\n" + mediainfo.name + "\n\n" + "My file duration is: " + conversion.ToString(), "Video Properties", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
}
}
//I then call callDialogBox() on a button click event
The output shows as per the below screenshot:
I want to be able to select multiple files and show the in the listbox but I get a:
Additional information: COM object that has been separated from its underlying RCW cannot be used.
When adding items to the listbox.
So two problems:
1. Being able to select and list filenames below one another
2. List the filenames in the listbox
With regards to point 1. , the below code snippet does somewhat achieve it but gives me the entire filename..
string[] selected = theDialog.FileNames;
foreach(string items in selected)
{
MessageBox.Show("Here are your filenames: " + items);
}
Gives me the entire path. Read up on some resources online but I can't seem to get what I want.
I had a look at: How do I drag n drop files into a ListBox with it showing the file path? and it didn't do the trick.
Try the following to add the filenames to the ListBox:
listBox1.Items.AddRange(selected);
Once this is done, you can then display your total duration.
Edit:
To list only file names, use following line.
listBox1.Items.AddRange(selected.Select(o=>System.IO.Path.GetFileName(o)).ToArray());
i am currently trying to redirect a path to save an image in a folder.
The Startup path is:
C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug
I am trying to change it so its like:
C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication
The code i am currently using is:
private void browseBtn_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
//open directory
open.Filter = "JPG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png|ALL Files (*.*)|*.*";
open.FilterIndex = 1;
if(open.ShowDialog() == DialogResult.OK)
{
if(open.CheckFileExists)
{
string paths = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
System.IO.File.Copy(open.FileName, paths + "\\Images\\sss.jpg");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any help or ideas on the matter? why isnt it taking off the characters so i can use images as the path
There is nothing wrong with your code:
string source =
#"C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug";
string path = source.Substring(0, source.Length - 10);
Console.WriteLine(path);
//resulting in C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication
....If:
You build the project as "Debug", not "Release"
The image directory and the sss.jpg image do exist.
But the way to get the path the way you do now is just... unsafe (at the very least). Try to use Path.Combine and string.Split("\\") instead:
string source = #"C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug";
string[] items = source.Split('\\');
string path = Path.Combine(string.Join("\\", items.Take(items.Length - 2)), "Images\\sss.jpg");
It seems, that you actually want to cut 2 subdirectories off and then combine with \Images\sss.jpg:
String source =
#"C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug";
String[] items = source.Split(new Char[] {
Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
String path = String.Join(
Path.DirectorySeparatorChar.ToString(), items.Take(items.Length - 2));
String result = Path.Combine(path, #"Images\sss.jpg");
There's nothing wrong with your code and should work just fine so long as the Images directory exists. Just use
if (!Directory.Exists(Path.Combine(path, "Images")))
Directory.Create(Path.Combine(path, "Images")))
Is there any reason not to just leverage DirectoryInfo? It looks like you just want to go up two directories. You should be able to use DirectoryInfo.Parent to get the path you need without needing to do string manipulation.
DirectoryInfo startupDirectory = new DirectoryInfo(Application.StartupPath);
DirectoryInfo twoDirectoriesUp = startupDirectory.Parent.Parent;
string fullDirectoryName = twoDirectoriesUp.FullName;
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#.
so basically i have a data grid view that goes into a file and loads all of the .txt file names into a data grid view. What i need to do is when i click on a certain file in data grid view, it will open up the contents of that file into a list view.
Can anyone help as i am stuck?
I am guessing its something like:
if data grid view value = .txt file in the folder then load contents into listview.
sounds easy enough just unsure how to code this.
Thank you
I have this so far but still does not work:
private void gridProfiles_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (gridProfiles.Rows[e.RowIndex].Cells[0].Value != null)
{
var path = gridProfiles.Rows[e.RowIndex].Cells[0].Value.ToString();
path = Path.Combine(rootDirectory + "\\Profiles\\", path);
if (File.Exists(path))
{
String[] lines = File.ReadAllLines(path);
foreach (var line in lines)
{
lstProcesses.Items.Add(path);
}
}
}
}
When i run this it gets ti if(file.exists(path) and then skips over it
route directory:
private static string rootDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\My File";
static void CreateDirectory()
{
string rootDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\My File";
if (!Directory.Exists(rootDirectory)) { Directory.CreateDirectory(rootDirectory); }
if (!Directory.Exists(rootDirectory + "\\Profiles")) { Directory.CreateDirectory(rootDirectory + "\\Profiles"); }
Looks like you create incorrect path, or you are reading incorrect cell value. Use overloaded Path.Combine which accept list of path parts. Also instead of adding path to list you should add line.
Following code will show you error message if file not exist with path where it tries to look for file. Also it will show error message if there is no file name in grid cell.
private void gridProfiles_CellClick(object sender, DataGridViewCellEventArgs e)
{
object value = gridProfiles.Rows[e.RowIndex].Cells[0].Value;
if (value == null)
{
MessageBox.Show("Cannot get file name from grid");
return;
}
var file = value.ToString();
var path = Path.Combine(rootDirectory, "Profiles", file); // create path
if (!File.Exists(path))
{
MessageBox.Show(path + " not found");
return;
}
foreach(string line in File.ReadLines(path))
lstProcesses.Items.Add(line); // add line instead of path
}