Copy a file and change the name - c#

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

Related

Show array data in richtext box

I added a RichTextBox control to my form. I want to show the data in an ArrayList in the RichTextBox. How can I do this?
try
{
string filepath = "";
string filename = "";
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "XML files|*.xml";
if (ofd.ShowDialog() == DialogResult.OK)
{
filepath = ofd.FileName;
txtPath.Text = filepath + filename;
XMLParser objxmlparser = new XMLParser();
ArrayList al =objxmlparser.readDataLogXml(txtPath.Text);
}
}
I think as long as objects in the ArrayList are simple data types, you could try
try
{
string filepath = "";
string filename = "";
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "XML files|*.xml";
if (ofd.ShowDialog() == DialogResult.OK)
{
filepath = ofd.FileName;
txtPath.Text = filepath + filename;
XMLParser objxmlparser = new XMLParser();
ArrayList al =objxmlparser.readDataLogXml(txtPath.Text);
for (int i = 0; i < al.Count; i++)
{
yourRichTextBox.Text += string.Format("{0}\r\n", al[i].ToString());
}
}
}
Otherwise, if the objects in the ArrayList are custom objects you created, then you need to override the ToString() method in the custom class that you defined
public class YourCustomClass
{
// Your Custom Fields
// Your Custom Methods
public override string ToString()
{
// Format how you want this object to display information about itself
// The {0}, {1}, etc... are place holders for your custom fields
return string.Format("Put what you want to display here: {0} {1} {2}", customField1, customField2, customField3)
}
}

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

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

get path without file name from saveFileDialog?

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

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