How to get the string in the button text?
private void btn_open_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
ReadCSV(openFileDialog1.FileName);
btn_open.Text = "filename here";
string targetdirectory = "D:\\Projects";
string filename = Path.GetFileNameWithoutExtension(target directory);
}
thanks for your help
When you select a file using OpenFileDialog, the OpenFileDialog.FileName contains the full path of the file selected.
Path.GetFileNameWithoutExtension() does just that, getting the file name without extension. However you need to pass an actual file path, not a directory. If you pass a directory path, it will simply retrieve the innermost directory name which is not what your desired outcome.
So what you should do is;
Get file name from OpenFileDialog.
Pass that to the Path.GetFileNameWithoutExtension() method.
Set the resulting string as the button text.
Also the correct usage of ShowDialog() is to check the return value; it returns true if the user clicked OK button, and false otherwise.
if(openFileDialog1.ShowDialog() == true)
{
string file = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
btn_open.Text = file;
}
Related
I have a fileupload control (FileUpload1) in my webform which I use to load an excel file. I use a button called btn_open to display it in a gridview on click.
I also save the file using FileUpload1.SaveAs() method in a server folder.
Now I have another button called btn_edit which on click needs to use the same
file that I just loaded to do another set of operations.
How do I pass this file/file path from btn_open_Click to btn_edit_Click? I do not want to specify the exact location on the code. There will be multiple times I will open new excel files so I don't want to specify the file path to the server for every new file.This needs to happen programatically. Also, I want to avoid using Interop if its possible.
The following code snippet might make things more clear as to what I want to do.
protected void btn_open_Click(object sender, EventArgs e)
{
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() == ".xlsx" || fileExtension.ToLower() == ".xls")
{
string path = Path.GetFileName(FileUpload1.FileName); //capture the file name of the file I have uploaded
path = path.Replace(" ", ""); // if there is any spacing between the file name it will remove it
FileUpload1.SaveAs(Server.MapPath("~/ExcelFile/") + path); //saves to Server folder called ExcelFile
String ExcelPath = Server.MapPath("~/ExcelFile/") + path; // Returns the physical file path that corresponds to the specified virtual path.
.
.
*code to display it in gridview*
.
.
}
else
{
Console.Writeline("File type not permissible");
}
}
protected void btn_edit_Click(object sender, EventArgs e)
{
//HOW DO I PASS THE ABOVE FILE HERE PROGRAMATICALLY WITHOUT SPECIFYING IT'S EXACT LOCATION ON THE SERVER??
}
Using Session variable helped me solve my problem. Hopefully it will be helpful to other people who might encounter similar issue.
On the first button (in my case btn_open_Click), add:
Session["myXlsPath"] = ExcelFilePath;
Note: "myXlsPath" is just a name I created for my Session variable. ExcelFilePath is the path of my excel file that I want to pass to the other button.
On the button you want to pass the file path to (in my case btn_edit_Click), add:
string ExcelFilePath = (string)Session["myXlsPath"];
I've tested the code and the directory gets the correct input, but for some reason it can't find it. Is there something I'm missing why I can't find any directory?
Here is my code pretty simplistic as of right now.
public partial class Form1 : Form
{
string fileName;
string dirName;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
dirName = textBox1.Text;
fileName = textBox2.Text;
if (System.IO.Directory.Exists(dirName))
{
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}
else
{
MessageBox.Show("Invalid Directory or File Name");
}
}
}
That's because I guess you're passing the directory path by an input control in this way "C:/examplePath/" and it should be declared in this way "C:\\examplePath" because the escape characters, and probably you'll get another error further because when you're asking for a file's existence, you must to declare it concatenating directory path plus filename (and its extension).
so the final string should be like this "c:\\exampleDir\\examplefile.ext"
or simply you should try:
dirName = string.Format("#{0}", textBox1.Text);
fullPathFile = string.Format("{0}/{1}", dirName, textBox2.Text);
And then you use "fullPathFile" instead of "fileName" variable.
Don't forget to debug your application for making sure what's the string values.
Based on your code, it appears fileName and dirName come from two different textbox controls. And you also dont do any sort of combining the file path (or so it appears). So when you call Directory.Exists() it makes sense that this would work but it can't find the file. When you use File.Exists() you need to pass in not only the file name but also the directory where its located. To do this use the Path.Combine() method.
if (System.IO.Directory.Exists(dirName))
{
string filePath = System.IO.Path.Combine(dirName, fileName);
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
else
{
MessageBox.Show("Invalid Directory or File Name");
}
}
I'm trying to upload multiple files and just get the filename of them.
When I'm trying to do that it just uploads one file.
So it uploads the files with the full path(And it works).
private void bChooseFolder_Click(object sender, EventArgs e)
{
CoreClass.OPENDIALOG.Multiselect = true;
string oldFilter = CoreClass.OPENDIALOG.Filter;
CoreClass.OPENDIALOG.Filter = "(*.csv) | *.csv";
if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK)
tbFolderPath.Text = string.Join(FileSeperator, CoreClass.OPENDIALOG.FileNames);// <-- this works, but here I get the full path
CoreClass.OPENDIALOG.Filter = oldFilter;
CoreClass.OPENDIALOG.Multiselect = false;
}
And so I get just the Filename but it uploads just one File:
private void bChooseFolder_Click(object sender, EventArgs e)
{
CoreClass.OPENDIALOG.Multiselect = true;
string oldFilter = CoreClass.OPENDIALOG.Filter;
CoreClass.OPENDIALOG.Filter = "(*.csv) | *.csv";
if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK)
tbFolderPath.Text = string.Join(FileSeperator, System.IO.Path.GetFileNameWithoutExtension(CoreClass.OPENDIALOG.FileName)); // <-- Doesn't work. Just one File.
CoreClass.OPENDIALOG.Filter = oldFilter;
CoreClass.OPENDIALOG.Multiselect = false;
}
OK, If you are developing WinForms app then you are using OpenFileDialog which contains 2 properties:
FileName gets or sets a string containing the file name selected in the file dialog box.
FileNames gets the file names of all selected files in the dialog box.
Then first one will never contains few files and you should use it only in Multiselect = false; mode.
If you need to show all file names in one textbox then you can use String.Join method and LINQ to enumerate collection and get file name without extension for each element:
if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK)
tbFolderPath.Text = string.Join(FileSeperator, CoreClass.OPENDIALOG.FileNames.Select(x => System.IO.Path.GetFileNameWithoutExtension(x)).ToArray()); // <-- Doesn't work. Just one File.
I have recently started to get an error which states my directory can not be found I have tried a number of ways to solve this but have yet to find a solution.
The method should allow the user to select an image for their computer and add it to a folder called images inside the applications folder structure. The problem is that when using the File.copy(imageFilename, path); it throws the error. I have tried changing the path and you will see from the code snip it. It is even doing it when the program itself has passed the file path for the application and is still throwing me the error.
this is the method.
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
System.IO.File.Copy(imageFile.FileName, path);
}
}
}
I am using VS2013 and have included the using Microsoft.win32
Any further information needed please ask.
Thanks
There are 2 things need to be taken into consideration
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
string path = AppDomain.CurrentDomain.BaseDirectory; // You wont need it
System.IO.File.Copy(imageFile.FileName, path); // Copy Needs Source File Name and Destination File Name
}
}
}
string path = AppDomain.CurrentDomain.BaseDirectory; You won need this because the default directory is your current directory where your program is running.
Secondly
System.IO.File.Copy(imageFile.FileName, path); Copy Needs Source File Name and Destination File Name so you just need to give the file name instead of path
so your updated code will be
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
System.IO.File.Copy(imageFile.FileName, SomeName + ".jpg"); // SomeName Must change everytime like ID or something
}
}
}
I'm not sure if that's the problem, but the File.Copy method expects a source file name and a target file name, not a source file name and directory: https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx
So, to make this work, in your case you'd have to do something like the following (namespaces omitted):
File.Copy(imageFile.FileName, Path.Combine(path, Path.GetFileName(imageFile.FileName));
Note that this will fail if the destination file exists, to overwrite it, you need to add an extra parameter to the Copy method (true).
EDIT:
Just a note, the OpenFileDialog.CheckFileExists does not return a value indicating if the selected file exists. Instead, it is a value indicating whether a file dialog displays a warning if the user specifies a file name that does not exist. So instead of checking this property after the dialog is closed, you should set it to true before you open it (https://msdn.microsoft.com/en-us/library/microsoft.win32.filedialog.checkfileexists(v=vs.110).aspx)
Can i get the full path from a filename such as get the full directory path from test.txt, Or is there a way i can save it
The reason im asking this is im making a application like Notepad++ some of you may of heard of it. When changing the tab control tab I want the form's text to be the full directory while the tabs text is just filename.format
My so far code
private void tabControl1_TabIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedTab.Text.StartsWith("New"))
{
int count = tabControl1.TabCount - 1;
this.Text = tabControl1.Controls[count].Text + " - My Note 1.0";
}
//It is a directory and i need to make the forms text the path here?
}
You can use System.IO.Path.GetFullPath:
var fullPath = Path.GetFullPath("test.txt");
If you pass in a short file name, it is expanded to a long file name.
If c:\temp\newdir is the current directory, calling GetFullPath on a file name such as test.txt returns c:\temp\newdir\test.txt.
And if you want to get path from that you use System.IO.Path.GetDirectoryName
var path = Path.GetDirectoryName(fullPath)
I think you should probably keep the full path and get the filename from the full path rather than the other way around. The key is to use a type representing a document, and let the tab view that document. If each tab refers to a document, and each document knows its full path, then you can get the short filename from the documents full path.
public class Document
{
public string FullPath { get; set; } // Full path to file, null for unsaved
public string FileName
{
get { return Path.GetFileName(FullPath); }
}
}
When a new tab is focused, get the document for the active tab and set the forms title from the FullPath of the document.
private void tabControl1_TabIndexChanged(object sender, EventArgs e)
{
Document activeDoc = GetDocumentFromActiveTab();
// Update win title with full path of active doc.
this.Text = (activeDoc.FullPath ?? "Unsaved document") + " MyApp" + version;
}
EDIT:
The key here is of course the method GetDocumentFromActiveTab() which isn't shown. You need to implement the data structures that manage your documents, and connects them to tabs. I did not include that in the answer, you need to try yourself. One idea is to make a type representing the entire application state including all tabs and documents.
public class Workspace
{
private Dictionary<SomeTypeOfView, Document> documentsOpenInViews;
// Methods to register a document to a tab, get document for a tab
// remove tab+document when tab is closed etc.
}
// not sure if this is what you want
say your filename with path is
string strFFL = #"C:\path\filename.format";
Console.WriteLine(System.IO.Path.GetFileName(strFFL)); //->filename.format
Console.WriteLine(System.IO.Path.GetDirectoryName(strFFL)); //-> C:\path
http://msdn.microsoft.com/en-us/library/system.io.path.getfilename(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx
I think this is actually backwards. I think you want to keep a full path to the file and be able to display the filename only on the tab. So I think you want Path.GetDirectory name.
From: http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx
string filePath = #"C:\MyDir\MySubDir\myfile.ext";
string directoryName;
int i = 0;
while (filePath != null)
{
directoryName = Path.GetDirectoryName(filePath);
Console.WriteLine("GetDirectoryName('{0}') returns '{1}'",
filePath, directoryName);
filePath = directoryName;
if (i == 1)
{
filePath = directoryName + #"\"; // this will preserve the previous path
}
i++;
}
/*
This code produces the following output:
GetDirectoryName('C:\MyDir\MySubDir\myfile.ext') returns 'C:\MyDir\MySubDir'
GetDirectoryName('C:\MyDir\MySubDir') returns 'C:\MyDir'
GetDirectoryName('C:\MyDir\') returns 'C:\MyDir'
GetDirectoryName('C:\MyDir') returns 'C:\'
GetDirectoryName('C:\') returns ''
*/