Streamreader read file on same directory - c#

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

Related

How to open PowerPoint file in resource file C#

I have a number of small PowerPoint files in my resources folder and I want to open them. I'm having issues doing this as my Resource.sendToPPTTemp is of type byte[] and to open the file I need it as a string. Is there a way I can open a file from resources as a string?
var file = Resources.sendToPPTTemp;
ppnt.Application ppntApplication = new ppnt.Application();
var _assembly = Assembly.GetExecutingAssembly();
var myppnt = ppntApplication.Presentations.Open(file.ToString());
ppntApplication.Visible = MsoTriState.msoTrue;
You need to give the path to your file to the Open method, not the binary representation. Either you have the path and pass it to the method or you have to create a file with your byte[].
I'd rather create a folder with all your PPT and store in your resource file the path to that folder. Then you can use the first method:
var di = new DirectoryInfo(Resources.PPTFolderPath);
foreach(var file in di.GetFiles())
{
var myppnt = ppntApplication.Presentations.Open(fi.FullName);
ppntApplication.Visible = MsoTriState.msoTrue;
[..]
}
But if you really want to store your PPT in the resource file, you can do it like this, with a temporary file for example:
var tmpPath = Path.GetTempFileName();
try
{
File.WriteAllBytes(tmpPath, Resources.sendToPPTTemp);
var myppnt = ppntApplication.Presentations.Open(tmpPath);
ppntApplication.Visible = MsoTriState.msoTrue;
[..]
}
finally
{
// you have to delete your tmp file at the end!!!
// probably not the better way to do it because I guess the program does not block on Open.
// Better store the file path into a list and delete later.
var fi = new FileInfo(tmpPath);
fi.Delete();
}

StreamWriter to project directory and sub directory?

I'm currently having an issue with my application and I'm starting to think it's just my logic. I can't figure it out even after browsing these forms and MSDN.
I'm trying to use StreamWriter to create a text document in my app directory and create sub folder containing that document. Currently it just keeps dumping the file in my apps exe directory.
string runTimeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string recipeDirectory = Path.Combine(runTimeDirectory, "Recipes");
if (!Directory.Exists(recipeDirectory))
{
//Recipes directory doesnt exist so create it
Directory.CreateDirectory(recipeDirectory);
}
// Write text to file
using (StreamWriter OutputFile = new StreamWriter(recipeDirectory + RecipeName + #".txt"))
{
Try this:
using (StreamWriter OutputFile = new StreamWriter(
Path.Combine(recipeDirectory, RecipeName + #".txt")))
The reason I think is that your recipeDirectory and RecipeName + #".txt" aren't separated by the backslash, so the file is written to the parent directory instead and named recipeDirectory + RecipeName + #".txt".
As an aside, I would also recommend you pass your RecipeName through a sanitizer function like this in case any name contains characters that can't be used in a file name:
internal static string GetSafeFileName(string fromString)
{
var invalidChars = Path.GetInvalidFileNameChars();
const char ReplacementChar = '_';
return new string(fromString.Select((inputChar) =>
invalidChars.Any((invalidChar) =>
(inputChar == invalidChar)) ? ReplacementChar : inputChar).ToArray());
}

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

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

Copy file to a different directory

I am working on a project where I want to copy some files in one directory to a second already existing directory.
I can't find a way to simply copy from one folder to another. I can find copy file to a new file, or directory to a new directory.
The way I have my program set up right now is I copy the file and leave it in same directory, then move that copy to the directory that I want.
Edit:
Thanks everyone. All of your answers worked. I realized what I did wrong, when i set the destination path I didn't add a filename. Everything works now, Thanks for the super speedy responses.
string fileToCopy = "c:\\myFolder\\myFile.txt";
string destinationDirectory = "c:\\myDestinationFolder\\";
File.Copy(fileToCopy, destinationDirectory + Path.GetFileName(fileToCopy));
File.Copy(#"someDirectory\someFile.txt", #"otherDirectory\someFile.txt");
works fine.
MSDN File.Copy
var fileName = "sourceFile.txt";
var source = Path.Combine(Environment.CurrentDirectory, fileName);
var destination = Path.Combine(destinationFolder, fileName);
File.Copy(source, destination);
Maybe
File.Copy("c:\\myFolder\\myFile.txt", "c:\\NewFolder\\myFile.txt");
?
This worked for me:
string picturesFile = #"D:\pictures";
string destFile = #"C:\Temp\tempFolder\";
string[] files = Directory.GetFiles(picturesFile);
foreach (var item in files)
{
File.Copy(item, destFile + Path.GetFileName(item));
}
I used this code and it work for me
//I declare first my variables
string sourcePath = #"Z:\SourceLocation";
string targetPath = #"Z:\TargetLocation";
string destFile = Path.Combine(targetPath, fileName);
string sourceFile = Path.Combine(sourcePath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
File.Copy(sourceFile, destFile, true);
If the destination directory doesn't exist, File.Copy will throw. This version solves that
public void Copy(
string sourceFilePath,
string destinationFilePath,
string destinationFileName = null)
{
if (string.IsNullOrWhiteSpace(sourceFilePath))
throw new ArgumentException("sourceFilePath cannot be null or whitespace.", nameof(sourceFilePath));
if (string.IsNullOrWhiteSpace(destinationFilePath))
throw new ArgumentException("destinationFilePath cannot be null or whitespace.", nameof(destinationFilePath));
var targetDirectoryInfo = new DirectoryInfo(destinationFilePath);
//this creates all the sub directories too
if (!targetDirectoryInfo.Exists)
targetDirectoryInfo.Create();
var fileName = string.IsNullOrWhiteSpace(destinationFileName)
? Path.GetFileName(sourceFilePath)
: destinationFileName;
File.Copy(sourceFilePath, Path.Combine(destinationFilePath, fileName));
}
Tested on .NET Core 2.1
NET6 - Extension method
[DebuggerStepThrough]
public static FileInfo CopyToDir(this FileInfo srcFile, string destDir) =>
(srcFile == null || !srcFile.Exists) ? throw new ArgumentException($"The specified source file [{srcFile.FullName}] does not exist", nameof(srcFile)) :
(destDir == null || !Directory.Exists(destDir)) ? throw new ArgumentException($"The specified destination directory [{destDir}] does not exist", nameof(destDir)) :
srcFile.CopyTo(Path.Combine(destDir, srcFile.Name), true);

Categories