get path without file name from saveFileDialog? - c#

I am try to get my path from SaveFileDialog without my file name in order to create a DirectoryInfo object
private void btnBrowseCapture_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialogBrowse2 = new SaveFileDialog();
saveFileDialogBrowse2.Filter = "Pcap file|*.pcap";
saveFileDialogBrowse2.Title = "Save an pcap File";
saveFileDialogBrowse2.ShowDialog();
if (saveFileDialogBrowse2.FileName != "")
{
string str = saveFileDialogBrowse2.FileName;
}
}

You can also use System.IO.Path.GetDirectoryName for this purpose
System.IO.Path.GetDirectoryName(filePath)

Use System.IO.FileInfo.DirectoryName property to get the full path of the directory of a file.
string fileName = #"C:\TMP\log.txt";
FileInfo fileInfo = new FileInfo(fileName);
Console.WriteLine(fileInfo.DirectoryName); // Output: "C:\TMP"
Using your example:
string str = saveFileDialogBrowse2.FileName;
FileInfo fileInfo = new FileInfo(str);
Console.WriteLine(fileInfo.DirectoryName);

string fileName = #"C:\TMP\log.txt";
FileInfo fileInfo = new FileInfo(fileName);
Console.WriteLine(fileInfo.DirectoryName);

You can use System.IO.Path.GetDirectoryName method:
Console.WriteLine(System.IO.Path.GetDirectoryName(Filename));

Related

Copy a file and change the name

I was asked to make a file copier that will change the name of a file, by adding "_Copy", but will keep the type of file.
For example:
c:\...mike.jpg
to:
c:\...mike_Copy.jpg
Here is my code:
private void btnChseFile_Click(object sender, EventArgs e)
{
prgrssBar.Minimum = 0;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Which file do you want to copy ?";
DialogResult fc = ofd.ShowDialog();
tbSource.Text = ofd.FileName;
tbDestination.Text = tbSource.Text + "_Copy";
}
You can use the classes System.IO.FileInfo and System.IO.Path to do what it appears you are attempting:
OpenFileDialog od = new OpenFileDialog();
if(od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
System.IO.FileInfo fi = new System.IO.FileInfo(od.FileName);
string oldFile = fi.FullName;
string newFile = oldFile.Replace(System.IO.Path.GetFileNameWithoutExtension(oldFile),
string.Format("{0}_Copy",
System.IO.Path.GetFileNameWithoutExtension(oldFile)));
MessageBox.Show(newFile);
}
Then you can call the following to perform the copy:
System.IO.File.Copy(oldFile, newFile);
You are appending the _Copy onto the end of the filename and not before the extension. You need to add it before the extension:
string destFileName = $"{Path.GetFileNameWithoutExtension(ofd.FileName)}_Copy{Path.GetExtension(ofd.FileName)}";
Or without C# 6:
string destFileName = String.Format("{0}_Copy{1}",
Path.GetFileNameWithoutExtension(ofd.FileName),
Path.GetExtension(ofd.FileName));
Then to get the full path to the file use:
string fullPath = Path.Combine(Path.GetDirectoryName(ofd.FileName, destFileName));
Then to perform the actual copy just use:
File.Copy(ofd.FileName, fullPath);

How to get path of a Folder and use with StreamWriter?

Folder path. Here's my current codes:
private void button2_Click(object sender, EventArgs e)
{
String Username = Nametxt.Text;
var directoryInfo = Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "F.U.T.U.R.E"));
directoryInfo.CreateSubdirectory(Username); // Create a Sub-Folder inside "F.U.T.U.R.E"
StreamWriter stream = new StreamWriter(Username + ".txt");
stream.WriteLine(passwordtxt.Text);
stream.Close();
}
From the current codes the text is being created in the software directory#.
Part 1:
On button click the software should create a folder entitle "F.U.T.U.R.E" then create a Sub-Folder with the NameString Username= textbox1.text.
Part2:
Creating a new StreamWriterinside the new Sub-Folder Username
Pass the full path of the file in the constructor of the StreamWriter:
String Username = Nametxt.Text;
DirectoryInfo directoryInfo = Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "F.U.T.U.R.E")).CreateSubdirectory(Username);
StreamWriter stream = new StreamWriter(Path.Combine(directoryInfo.FullName, Username + ".txt"));
You will need to pass the full path, such as
StreamWriter stream = new StreamWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "F.U.T.U.R.E", Username) + Username + ".txt")

Confusion in reading file using FolderBrowserDialog

which i used earlier (FileuploadControl tool used)
inside button click method
if (FileUploadControl.HasFile)
{
filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
string lines;
string root = Server.MapPath("~/");
string Template = root + filename;
using (StreamReader reader = new StreamReader(Template))
{
while ((lines = reader.ReadLine()) != null)
list.Add(lines); // Add to list.
}
//file is now in list
//MORE IMPORTANT CODE
}
But now I am just using FolderDialog
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.ShowNewFolderButton = true;
DialogResult result = folderDialog.ShowDialog();
if (result == DialogResult.OK) {
textBox8.Text = folderDialog.SelectedPath;
Environment.SpecialFolder root = folderDialog.RootFolder
//...
}
How can i read the file so that i can only use the FolderBrowserDialog to read an entire file and extract data?
I guess you are working in Windows Forms now if you are using FolderDialog.
You should use better OpenFileDialog if you want the user to check a FILE, not a Folder.
You can read the file using System.IO classes once you have the path.
If the file is text for example you can do:
string FinalPath = OpenFileDialog.FileName;
string Text= System.IO.File.ReadAllText(FinalPath);
you can also read the file into byte()
byte[] file = System.IO.File.ReadAllBytes(FinalPath);

Get only FolderName into datatable

I am trying to just get the subfoldername and not the FULLNAME into a serparate column in my datatable. Please help.
protected void Page_Load(object sender, EventArgs e) {
DataTable ReportsDT = new DataTable("ReportsDT");
ReportsDT.Columns.Add("Name");
ReportsDT.Columns.Add("FolderName");
DirectoryInfo DirInfo = new DirectoryInfo(Server.MapPath("Reports"));
DataRow ReportDTRow = ReportsDT.NewRow();
foreach (FileInfo fi in DirInfo.GetFiles("*.*", SearchOption.AllDirectories)) {
ReportDTRow = ReportsDT.NewRow();
ReportDTRow["Name"] = fi.Name;
ReportDTRow["FolderName"] = fi.FullName;
ReportsDT.Rows.Add(ReportDTRow);
}
}
You can use DirectoryInfo to get information on a given directory. You have a copy supplied in the FileInfo instance under fi.Directory:
foreach (FileInfo fi in DirInfo.GetFiles("*", SearchOption.AllDirectories)) {
ReportDTRow = ReportsDT.NewRow();
ReportDTRow["Name"] = fi.Name;
ReportDTRow["FolderName"] = fi.Directory.Name;
ReportsDT.Rows.Add(ReportDTRow);
}
See sample code below:
string[] folders = fi.FullName.Split('\\');
string subFolderName = folders[folders.Length - 2];
I believe you are looking for
ReportDTRow["FolderName"] = fi.Directory.Name;
You could also just split the string on the path separator and parse it out yourself, but the above should work nicely assuming I understand what you want.

How to Get File Size,File Name,File Ext In C# Windows?

im new to c#.net,any one let me know How to Get File Size,File Name,File Ext In C# Windows.
im using open file dialog in c#..im getting only the path..i dont know how to get the file name and size..
my code is :
openFileDialog1.ShowDialog();
openFileDialog1.Title = "Select The File";
openFileDialog1.InitialDirectory = "C:";
openFileDialog1.Multiselect = false;
openFileDialog1.CheckFileExists = false;
if (openFileDialog1.FileName != "")
{
txtfilepath1.Text = openFileDialog1.FileName;
var fileInfo = new FileInfo(openFileDialog1.FileName);
lblfilesize1.Text = Convert.ToString(openFileDialog1.FileName.Length);
lblfilesize=
lblfilename=
}
Size FileInfo.Length
Name FileInfo.Name
Extension FileInfo.Extension
You don't need to use any other class. You're already using FileInfo.
You can use FileInfo Class. File Info
using System;
using System.IO;
class Program
{
static void Main()
{
// The name of the file
const string fileName = "test.txt";
// Create new FileInfo object and get the Length.
FileInfo f = new FileInfo(fileName);
long s1 = f.Length;
// Change something with the file. Just for demo.
File.AppendAllText(fileName, " More characters.");
// Create another FileInfo object and get the Length.
FileInfo f2 = new FileInfo(fileName);
long s2 = f2.Length;
// Print out the length of the file before and after.
Console.WriteLine("Before and after: " + s1.ToString() +
" " + s2.ToString());
// Get the difference between the two sizes.
long change = s2 - s1;
Console.WriteLine("Size increase: " + change.ToString());
}
}
For Extension You can use Path.GetExtension()
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx

Categories