Confusion in reading file using FolderBrowserDialog - c#

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);

Related

C# could not find file 'filepath'

I'm getting the 'cannot be found' error although the file does exist and the path is right. I have tried AudiosInfo.txt.txt and it does not work.
FileStream f = new FileStream("AudiosInfo.txt", FileMode.Open);
StreamReader s = new StreamReader(f);
string l=s.ReadLine();
MessageBox.Show(l);
When you are using,
FileStream f = new FileStream("AudiosInfo.txt", FileMode.Open);
you have to ensure that, AudiosInfo.txt file must be stored in your solution's \bin\Debug folder.
Otherwise you have to give the full path.
This is how you can find the full path: right click on the AudiosInfo.txt file, click on properties, click on the details tab and take a look at the folder path.
Might need to use to find the the path
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++;
}
/*

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);

Replace SaveFileDialog to saving in code

I have such code that saves bin file, but user has to choose file
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Binary File (*.bin)|*.bin";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
Question.PersistObject(questions, myStream);
myStream.Close();
}
}
But I want to choose file in code, and if a file with such name doesn't exist, then create it. How to set in myStream that file?
Replace all your logic related to the OpenFileDialog with File.Open:
using (var myStream = File.Open(someFilePath, FileMode.OpenOrCreate))
{
Question.PersistObject(questions, myStream); // do something with the stream
}
The OpenOrCreate file mode will open the file if it exists, or create it if it does not.
The using statement will take care of closing the stream for you.
One option would be to have a base name and append a number:
string templateName = "myfile{0}.bin";
string finalName;
int count = 0;
do {
finalName = String.Format(templateName, count++);
} while (File.Exists(finalName);
Or, if you don't care about the name, use Path.GetTempFileName
Then pass that name to StreamWriter:
using (StreamWriter writer = new StreamWriter(finalName))
{
// Write stuff
}

OpenFileDialog.RestoreDirectory fails for %temp% location? Bug or Feature

In my app I used OpenFileDialog to select a file from temp location (%temp%). Now when I again use OpenFileDialog, it opens from some other location. This feature is working fine if any folder other than temp is selected.
Is this a bug or a feature or Technical limitation?
I wrote this code.
public string[] OnOpenFile(string filetype)
{
string strReturn = null;
string[] strFilename = null;
System.Windows.Forms.OpenFileDialog fdlg = new System.Windows.Forms.OpenFileDialog();
fdlg.Title = "Select an Excel file to Upload.";
fdlg.Filter = filetype;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
strFilename = fdlg.FileNames;
}
return strFilename;
}
You can use InitialDirectory property documented at http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.initialdirectory.aspx
in your example:
fdlg.InitialDirectory = Path.GetTempPath();
Running this C# Proram in LinqPad produces wanted result
void Main()
{
OnOpenFile();
OnOpenFile();
OnOpenFile();
}
public string[] OnOpenFile()
{
string strReturn = null;
string[] strFilename = null;
System.Windows.Forms.OpenFileDialog fdlg = new System.Windows.Forms.OpenFileDialog();
fdlg.Title = "Select an Excel file to Upload.";
//fdlg.Filter = filetype;
fdlg.InitialDirectory = Path.GetTempPath();
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
strFilename = fdlg.FileNames;
}
return strFilename;
}
If you comment
fdlg.InitialDirectory = Path.GetTempPath();
you can achieve wanted behavior.
Each time file is selected in folder, that folder in OpenFileDialog opens.
If you press Cancel you have to handle your selected path diffrently - in some string variable, then when you open OpenFileDialog again you set InitialDirectory

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