How to copy a file in C# - c#

I want to copy a file from A to B in C#. How do I do that?

Without any error handling code:
File.Copy(path, path2);

The File.Copy method:
MSDN Link

Use the FileInfo class.
FileInfo fi = new FileInfo("a.txt");
fi.CopyTo("b.txt");

This should work!
using System.IO;
...
var path = //your current filePath
var outputPath = //the directory where you want your (.txt) file
File.Copy(path,outputPath);

System.IO.File.Copy

Related

How to get file name from a path in c#

I want to extract the filename from a file path in C#.
For example:
textBox1.Text = "C:\Users\Elias\Desktop\image.png"
I want to copy the file name: "image.png" to the textBox2
How can i do that?
Use the static Path.GetFileName method in System.IO:
Path.GetFileName(#"C:\Users\Elias\Desktop\image.png"); // --> image.png
regarding your example:
textBox2.Text = Path.GetFileName(textBox1.Text);
System.IO.FileInfo class can help with parsing that information:
textBox2.Text = new FileInfo(textBox1.Text).Name;
MSDN documentation on the FileInfo class:
https://msdn.microsoft.com/en-us/library/system.io.fileinfo(v=vs.110).aspx

Regex to get whatever the parent directory of my file is in string file path

I have a string file path and I am looking to get the name of the folder that is next up from the file.
Here is my file path:
Test/FilePathNeeded/testing.txt
I am sure there is a way to get FilePathNeeded from the file path above with regex, I just am not sure how it would be done. My thought is that the amount of directories that testing.txt is in should not matter, but the folder needed would always be one up from the file.
I hope this makes sense. Please let me know if it doesn't. Would anyone be able to help?
Without Regex, You can use:
string directory = new DirectoryInfo(
Path.GetDirectoryName("Test/FilePathNeeded/testing.txt")
).Name;
Path.GetDirectoryName will return Test/FilePathNeeded that you can use in the constructor of DirectoryInfo and get Name.
Another option is to use Directory.GetParent like:
var directory = Directory.GetParent("Test/FilePathNeeded/testing.txt").Name;
Simply use:
var dir = new FileInfo("Test/FilePathNeeded/testing.txt").Directory.Name;
This will return FilePathNeeded
Use the FileInfo class:
var fileInfo = new FileInfo(#"Test/FilePathNeeded/testing.txt");
var directoryInfo = fileInfo.Directory;
var parentDirectoryName = directoryInfo.Name;

Move a file to under a directory using C#

string str = "C:\\efe.txt";
string dir = "D:\\";
I want to move or copy "efe.txt" file under "D:\" directory. How can I do that.
thanks for your advice.....
As others have mentioned you want to use File.Move, but given your input you'll also want to use Path.Combine and Path.GetFileName like so
string str = "C:\\efe.txt";
string dir = "D:\\";
File.Move(str, Path.Combine(dir, Path.GetFileName(str)));
From MSDN: How to: Copy, Delete, and Move Files and Folders (C# Programming Guide):
// Simple synchronous file move operations with no user interface.
public class SimpleFileMove
{
static void Main()
{
string sourceFile = #"C:\Users\Public\public\test.txt";
string destinationFile = #"C:\Users\Public\private\test.txt";
// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);
// To move an entire directory. To programmatically modify or combine
// path strings, use the System.IO.Path class.
System.IO.Directory.Move(#"C:\Users\Public\public\test\", #"C:\Users\Public\private");
}
}
Try File.Move
using System.IO;
...
string src = "C:\\efe.txt";
string dest = "D:\\efe.txt";
File.Move(src, dest);

Save all the folder structure with DotNetZip

I did this simple code with the latest version of the library DotNetZip, for some reason when I add a file I get all the folder structure. For example if I add:
C:\one folder\two folders\File.doc
Inside the zip file I will have
one folder\two folders\File.doc
But my expected result would be to have just the file.doc
This is my code, I don't know if I am doing something wrong or what..:
//C#
public static void MethodOne(string PathInput, int LimitKb=0, bool DeleteInput=false)
{
using (ZipFile zip = new ZipFile())
{
//add file to zip
zip.AddFile(PathInput);
//save it
zip.Save(PathInput + ".zip");
}
}
Thanks! :)
Use the overloaded, two-parameter call to AddFile where you specify the internal directory structure.
zip.AddFile(filename, String.Empty);
I think that would do what you want but I can't easily test it.

Streamreader to a relative filepath

I was wondering, if anyone could tell me how to point a StreamReader to a file inside the current working directory of the program.
E.g.: say I have program Prog saved in the directory "C:\ProgDir\". I commit "\ProgDir" to a shared folder. Inside ProgDir is another directory containing files I'd like to import into Prog (e.g. "\ProgDir\TestDir\TestFile.txt") I'd like to make it so that the StreamReader could read those TestFiles, even when the path to the directory has changed;
(E.G., on my computer, the path to the Testfiles is
C:\ProgDir\TestDir\TestFile.txt
but on the other person's computer, the directory is
C:\dev_code\ProgDir\TestDir\TestFile.txt
).
How would I get a StreamReader to be ale to read from TestFile.txt on the other person's computer? (to clarify, the filenames do not change, the only change is the path ProgDir)
I tried the following:
string currentDir = Environment.CurrentDirectory;
DirectoryInfo directory = new DirectoryInfo(currentDir);
FileInfo file = new FileInfo("TestFile.txt");
string fullDirectory = directory.FullName;
string fullFile = file.FullName;
StreamReader sr = new StreamReader(#fullDirectory + fullFile);
( pulled this from : Getting path relative to the current working directory?)
But I'm getting "TestFile does not exist in the current context". Anyone have any idea as to how I should approach this?
Thank you.
Is the Folder "TestDir" always in the executable directory?
if so, try this
string dir =System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location);
string file = dir + #"\TestDir\TestFile.txt";
This will give you the path of the exe plus the folder inside it and the textfile
You can use the GetFullPath() method. Try this:
string filePath = System.IO.Path.GetFullPath("TestFile.txt");
StreamReader sr = new StreamReader(filePath);
A few things:
First, FileInfo.FullName gives the absolute path for the file, so you don't need to prepend the full directory path before the file in the StreamReader instance.
Second, FileInfo file = new FileInfo(TestFile.txt); should fail unless you actually have a class called TestFile with a txt property.
Finally, with almost every File method, they use relative paths already. So you SHOULD be able to use the stream reader on JUST the relative path.
Give those few things a try and let us know.
Edit: Here's what you should try:
FileInfo file = new FileInfo("TestFile.txt");
StreamReader sr = new StreamReader(fullFile.FullName);
//OR
StreamReader sr = new StreamReader("TestFile.txt");
However, one thing I noticed is that the TestFile is located in TestDir. If your executable is located in ProgDir as you're stating, then this will still fail because your relative path isn't right.
Try changing it to TestDir\TestFile.txt instead. IE: StreamReader sr = new StreamReader("TestDir\TestFile.txt");
The FileInfo constructor takes a single parameter of type string. Try putting quotes around TestFile.txt.
Change
FileInfo file = new FileInfo(TestFile.txt);
to
FileInfo file = new FileInfo("TestFile.txt");
Unless TestFile is an object with a property named txt of type string, in which case you have to create the object before trying to use it.
The easiest way would be to just use the file name (not the full path) and "TestDir" and give the StreamReader a relative path.
var relativePath = Path.Combine(".","TestDir",fileName);
using (var sr = new StreamReader(relativePath))
{
//...
}
I had a similar issue and resolved it by using this method:
StreamReader sr = File.OpenText(MapPath("~/your_path/filename.txt"))
This could be a good option if you need a more relative path to the file for working with different environments.
You can use path.combine to get the current directory to build and then combine the file path you need
new StreamReader(Path.Combine(Environment.CurrentDirectory, "storage"));
System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath)

Categories