Move a file to under a directory using C# - 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);

Related

Streamreader read file on same directory

I want to read a CSV file which is located at the same directory as my code.
I want to read the content of the .csv
public static void InitializeItems()
{
itemList = new Dictionary<int, Item>();
string filePath = Path.Combine(Directory.GetCurrentDirectory(), "\\Items.csv");
using (StreamReader reader = new StreamReader(filePath))
{
int lineCounter = 0; // Do I really need such a counter for the current line?
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] values = line.Split(',');
string name = values[0];
itemList.Add(lineCounter, new Item(name));
lineCounter++;
}
}
}
private static Dictionary<int, Item> itemList;
By doing so I get a System.IO.FileNotFoundException exception. The file C:\Items.csv does not exist.
Directory.GetCurrentDirectory() returns me the path to the .exe file.
What is wrong with the path?
Current directory is not necessary the directory where exe has been executed:
// Current directory can be whatever you want:
Environment.CurrentDirectory = #"c:\SomeDirectory";
If you are looking for the exe path you can try
string exePath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
In your case:
using System.Reflection;
...
string filePath = Path.Combine(
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
"Items.csv");
Edit: You can simplify the code (get rid of StreamReader) with a help of Linq:
var itemList = File
.ReadLines(filePath)
.Select((line, index) => new {
value = new Item(line.SubString(0, line.IndexOf(',') + 1)),
index = index
})
.ToDictionary(item => item.index, item => item.value);
The way to get the path of the .exe file like:
AppDomain.CurrentDomain.BaseDirectory
Then, you must put BuildAction as Content. With this, the file is copied to the folder exe after build.
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "file.csv");
To answer your direct question, what is wrong: You can not have your file starting with a backslash when using Path.Combine. You should write it as this:
string filePath = Path.Combine(Directory.GetCurrentDirectory(), "Items.csv");
Edit:
By default the 'CurrentDirectory' points to your exe file, unless you change it in code or in a shortcut.
First it is advisable to create a new folder in your project to store files and name it MyFiles,
then lets say your file is a csvfile and named test.csv
so this can be accessed like this :
string testFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"MyFiles\test.csv");

How to move subfolder with files to another directory in asp.net C#

I want to copy and paste sub-folders of source folder ABC To destination folder. But it is not working. Here is my C# code, it work's fine but it copies the whole folder instead of only the sub-folders.
// string fileName = "test.txt";
string sourcePath = "D:\\Shraddha\\Demo_Web_App\\Source";
string targetPath = "D:\\Shraddha\\Demo_Web_App\\Destination";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath);
string destFile = System.IO.Path.Combine(targetPath);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
// System.IO.File.Copy(sourceFile, destFile, true);
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
//fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
Alright, here we go:
This doesn't really makes sense. If targetPath exists, create targetPath folder?
if (System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
You probably meant:
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
What you need to do first is, getting all directories to begin with:
var allDirectories = Directory.GetDirectories(targetPath, "*", SearchOption.AllDirectories);
then you can loop through allDirectories with foreach, find all files in each folder and copy the contents.
The following line cannot work like provided:
destFile = System.IO.Path.Combine(targetPath);
File.Copy expects a path to a file where you want to copy the content from "s", but you are providing only the destination folder. You have to include a filename in the Path.Combine method.
If you parse the path strings with the Path.GetFileName method for example, you can pass the result (only the filename without full source path) as an additional argument to Path.Combine to generate a valid destination path.
Additionally, like uteist already said, you have to get all subdirectories first, because in your code example, you're only copying the files, directly placed under your root source folder.
To keep the Directory structure
foreach (var dir in System.IO.Directory.GetDirectories(sourcePath))
{
var dirInfo = new System.IO.DirectoryInfo(dir);
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(targetPath, dirInfo.Name));
foreach (var file in System.IO.Directory.GetFiles(dir))
{
var fileInfo = new System.IO.FileInfo(file);
fileInfo.CopyTo(System.IO.Path.Combine(targetPath, dirInfo.Name, fileInfo.Name));
}
};

C# absolute path with streamReader

I have an issue with the reading a file in C#
I have two different locations for .exe (both different) and reading the same .xml file. So when I give the path like this:
TextReader textReader = new StreamReader(#"../../../TrajectoryGen/obstacleList.xml");
it is able to read from one location ( which is 3 folders behind as used in the path) but not from another location (which is only 2 folders behind)
How do I fix this problem so that it works from both folders?
First way, this relies on you knowing one of the parent folder's names.
const string FILENAME = "obstacleList.xml";
const string FOLDER = "TrajectoryGen";
string path = Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
do
{
path = Path.GetDirectoryName(path);
} while (!Path.GetFileName(path).Equals(FOLDER, StringComparison.OrdinalIgnoreCase));
string filepath = String.Format("{0}{1}{2}", path, Path.DirectorySeparatorChar, FILENAME);
^^ You can also use a partial path in the FILENAME like the example below incase you need to into directories once you are at your "base" folder that you know the name of.
Second way blindly continues up directories
const string FILENAME = #"TrajectoryGen\obstacleList.xml";
string path = Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
string filepath;
do
{
path = Path.GetDirectoryName(path);
//pump
filepath = String.Format("{0}{1}{2}", path, Path.DirectorySeparatorChar, FILENAME);
} while (!File.Exists(filepath));
Both require "using System.IO;" and both have no error handling implemented and will throw NullReferenceException if the file/folder is not found.
I purposely used the do-while loop because the definition of path will included the executable name.

How to combine two path

I have the code below and I get the result like this
C:\\Users\\Administrator\\Projects\\CA\\Libraries\\ConvertApi-DotNet\\Example\\word2pdf-console\\bin\\Release\\\\..\\..\\..\\..\\test-files\\test.docx
The file is found but I would like to show user this path and the formating is not user friendly. I would like to get
C:\\Users\\Administrator\\Projects\\CA\\Libraries\\test-files\\test.docx
I have tried to use Path.Combine but it do not work.
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string inFile = baseDirectory + #"\..\..\..\..\test-files\test.docx";
You could use a combination of Path.Combine and Path.GetFullPath:
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var file = #"..\..\..\..\test-files\test.docx";
string inFile = Path.GetFullPath(Path.Combine(baseDirectory, file));
Description
You say that the file is found.
Then you can use FileInfo (namespace System.IO) for that.
Sample
FileInfo f = new FileInfo(fileName);
f.Exists // Gets a value indicating whether a file exists.
f.DirectoryName // Gets a string representing the directory's full path.
f.FullName // Gets the full path of the directory or file.
More Information
MSDN - FileInfo Class

C#: Creating a new FileInfo in a directory that you have the DirectoryInfo of

I was just wondering when you have for example:
var dir = new DirectoryInfo(#"C:\Temp");
Is there an easier/clearer way to add a new file to that directory than this?
var file = new FileInfo(Path.Combine(dir.FullName, "file.ext"));
I'm thinking I can probably just make an extension method or something, but curious if something already exists that can't see here... I mean the DirectoryInfo does have GetFiles() method for example.
What is it that you want to do? The title says "Creating a new file". A FileInfo object is not a file; it's an object holding information about a file (that may or may not exist). If you actually want to create the file, there are a number of ways of doing so. One of the simplest ways would be this:
File.WriteAllText(Path.Combine(dir.FullName, "file.ext"), "some text");
If you want to create the file based on the FileInfo object instead, you can use the following approach:
var dir = new DirectoryInfo(#"C:\Temp");
var file = new FileInfo(Path.Combine(dir.FullName, "file.ext"));
if (!file.Exists) // you may not want to overwrite existing files
{
using (Stream stream = file.OpenWrite())
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write("some text");
}
}
As a side note: it is dir.FullName, not dir.FullPath.
Why don't you use:
File.Create(#"C:\Temp\file.ext");
or
var dir = new DirectoryInfo(#"C:\Temp");
File.Create(dir.FullName + "\\file.ext");
While there does exist Directorynfo.GetFiles() methods, they only return files that actually exist on disk. Path.Combine is about hypothetical paths.
Try these extension methods:
public static FileInfo CombineWithFileName(this DirectoryInfo directoryInfo, string fileName)
{
return new FileInfo(Path.Combine(directoryInfo.Name, fileName));
}
public static DirectoryInfo CombineWithDirectoryName(this DirectoryInfo directoryInfo, string directoryName)
{
return new DirectoryInfo(Path.Combine(directoryInfo.Name, directoryName));
}

Categories