c# .dat file assign to variable - c#

how can i assign a to a variable, which is located at the same project, for example at my project i created a folder named App_Data and for example the file is file.dat , how can i assign the file at a variable,.. for example:
var file = App_Data/file.dat
I need it to be assigned to a variable because i will be using that variable as a parameter to a method,.. it used to be :
var file= HttpContext.Current.Request.MapPath("/App_Data/file.dat");
but now i want the path to be at the same project
if it should be absolute path it should be fine too

The MapPath should give you the absolute location of the file on disk from a relative url to the root of your website:
var absoluteFileLocation = HostingEnvironment.MapPath("~/App_Data/file.dat");
This should return something like:
c:\inetpub\wwwroot\MyWebSite\App_Data\file.dat
UPDATE:
It looks like you are trying to retrieve the contents of the file, not the location. Here's how this could be done:
var absoluteFileLocation = HostingEnvironment.MapPath("~/App_Data/file.dat");
string fileContents = System.IO.File.ReadAllText(absoluteFileLocation);

You need to read the file using one of the available methods (Streams, Readers, etc).
The easiest would be:
string fileContent = File.ReadAllText(fileNameAndPath);
where the variable fileNameAndPath contains the full path and file name to the file as described by Darin Dimitrov.

Your intention isn't exactly clear, anyway:
if you want file stats:
System.IO.File file = new System.IO.File("~/App_Data/file.dat");
if you want the file content use:
public static string readFileContent(String filename)
{
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(filename))
return sr.ReadToEnd();
}
catch { return String.Empty; }
}

Related

How to get a specific file from directory in C#

Using Directory.GetFiles() returns all the files in the directory as follows:
var sqlFiles = Directory.GetFiles($"{AppDomain.CurrentDomain.BaseDirectory}Content\\DbScripts\\","*.sql");
Actually I need a specific file from that directory. What I have tried so far as follows but don't work!
var localizationSqlFile = Directory.GetFiles($"{AppDomain.CurrentDomain.BaseDirectory}Content\\DbScripts\\Localizations.sql").FirstOrDefault();
It throws expection:
The directory name is invalid.\r\n
Is there any method in C# to get a single file from a directory? If not then what will be most efficient way?
If you want to get the bytes of a certain file and you already have the full path, you can use the static method File.ReadAllBytes
var fileBytes = File.ReadAllBytes(myPath);
If you want to get file infos, you can create a new FileInfo object
var fileInfo = new FileInfo(myPath);
If you just want to check, if a file exists, you can also use the method File.Exist
if (File.Exists(myPath))
You can get the file from your sqlFiles returned
var sqlFiles = Directory.GetFiles($"{AppDomain.CurrentDomain.BaseDirectory}Content\\DbScripts\\","*.sql");
var yourFile = sqlFiles.FirstOrDefault(x=> Path.GetFileName(x) == "Localizations.sql");

Can't create folder structure with variable

I am trying to create a folder with a variable that can change, I am using
System.IO.Directory.CreateDirectory
When I hardcode a value like so:
var folder = #"C:\Users\Laptop\Documents\bot\random string here"
It creates that directory, but when I pass data to my method and try and use it like so:
var folder = #"C:\Users\Laptop\Documents\bot\" +
articlename.Replace(" ", "_");
System.IO.Directory.CreateDirectory(folder);
It doesn't create it nor break. How can I use the variable to create a folder like that?
My article is a random string like "hello this is a article yadda"
I solved by adding my paths together correctly as below
string path = root +"/"+ newfolder;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
// To move a file or folder to a new location:
//System.IO.File.Move(fi.FullName, path);
}

how to verify if an input read from console is a file name or a file full path

I have a console application in C# and I would like to load an xml file, the path to the file is provided via console.readline(). But, I would like to load the file from the provided path but if the user only provides the name of the file I would like to search for it in the local folder from where the application is running. How can I know when I get only a file name as an input or a file full path.
I managed that using: var isFileNameOnly = ((xmlFilePath.IndexOf("\\")) == -1);
But this ugly and probably very buggy.
Full code:
var xmlFilePath = Console.ReadLine();
var xmlFile = new XmlDocument();
var isFileNameOnly = ((xmlFilePath.IndexOf("\\")) == -1);
try
{
if (isFileNameOnly)
{
xmlFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, xmlFilePath);
}
xmlFile.Load(xmlFilePath);
}
Thx
You can check if the file name entered by user actually exists using Exists() method. If it returns true load the file.
File.Exists(xmlFilePath)
Also XmlDocument.Load() if provided only file name will try to find the file in the BaseDirectory itself. So if file.Exists() return true you can assume XmlDocument.Load will load it whether it is local or absolute path.
This will return false:
bool isFolder = Path.IsPathRooted(#"Text.txt");
This will return true:
bool isFolder = Path.IsPathRooted(#"C:\Text");
Your approach is the same that I would have chosen. If the param doesn't contain any directory delimiter char, then it must be a filename only. Maybe it would be a little more elegant if you did it like this:
bool isFileNameOnly = !xmlFilePath.Contains(Path.DirectorySeparatorChar.ToString());

C# console application generate CSV

I have a function that returns a File. The file is created by a String, like this:
return File(System.Text.Encoding.Default.GetBytes(data.getCSV()), "text/csv", "Report.csv");
How can i generate this File to a .csv file in my folder?
According to your use of the File() method, you seem to use an (Api)Controller in a console application. Don't do this. Put business logic in a class library:
public byte[] GenerateCsv()
{
// ...
return System.Text.Encoding.Default.GetBytes(data.getCSV());
}
Then you can do something like this:
var csvData = BusinessLogic.GenerateCsv();
System.IO.File.WriteAllBytes("Report.csv", csvData);
And the same from your (Api)Controller:
var csvData = BusinessLogic.GenerateCsv();
return File(csvData, "text/csv", "Report.csv");
var directory = Directory.GetCurrentDirectory(); // assuming that the folder you are looking for is the project directory.
using(var fs = new FileStream(directory + fileName + extension))
{
using(var sw = new StreamWriter(fs))
{
//use sw to write in the appropriate way.
}
}
Maybe you mean
string path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
you can get path to your folder, then you can find csv file in this folder and then overwrite it(or do something else).

c# open file, path starting with %userprofile%

I have a simple problem. I have a path to a file in user directory that looks like this:
%USERPROFILE%\AppData\Local\MyProg\settings.file
When I try to open it as a file
ostream = new FileStream(fileName, FileMode.Open);
It spits error because it tries to add %userprofile% to the current directory, so it becomes:
C:\Program Files\MyProg\%USERPROFILE%\AppData\Local\MyProg\settings.file
How do I make it recognise that a path starting with %USERPROFILE% is an absolute, not a relative path?
PS: I cannot use
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Because I need to just open the file by its name. User specifies the name. If user specifies "settings.file", I need to open a file relative to program dir, if user specifies a path starting with %USERPROFILE% or some other thing that converts to C:\something, I need to open it as well!
Use Environment.ExpandEnvironmentVariables on the path before using it.
var pathWithEnv = #"%USERPROFILE%\AppData\Local\MyProg\settings.file";
var filePath = Environment.ExpandEnvironmentVariables(pathWithEnv);
using(ostream = new FileStream(filePath, FileMode.Open))
{
//...
}
Try using ExpandEnvironmentVariables on the path.
Use the Environment.ExpandEnvironmentVariables static method:
string fileName= Environment.ExpandEnvironmentVariables(fileName);
ostream = new FileStream(fileName, FileMode.Open);
I use this in my Utilities library.
using System;
namespace Utilities
{
public static class MyProfile
{
public static string Path(string target)
{
string basePath =
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
#"\Automation\";
return basePath + target;
}
}
}
So I can simply use e.g. "string testBenchPath = MyProfile.Path("TestResults");"
You can use the Environment.Username constant as well. Both of the %USERPROFILE% and this Environment variable points the same( which is the currently logged user). But if you choose this way, you have to concatenate the path by yourself.

Categories

Resources