In my project there is a folder and in that folder there is text file. I want to read that text file
string FORM_Path = #"C:\Users\...\Desktop\FormData\Login.txt";
bool first = true;
string line;
try
{
using (StreamReader streamReader = File.OpenText(FORM_Path))
{
line = streamReader.ReadLine();
}
}
but I always get an error - file does not exist. how can i solve the problem in the path of text file.
Make sure your file's properties are set to copy the file to output directory. Then you can use the following line to get full path of your text file:
string FilePath = System.IO.Path.Combine(Application.StartupPath, "FormData\Login.txt");
You path is not in correct format. Use #".\FormData\Login.txt" instead of what you have
You are trying to give relative path instead of physical path. If you can use asp.net use Server.MapPath
string FORM_Path = Server.MapPath("~/FormData/Login.txt");
If the text file is in execution folder then you can use AppDomain.BaseDirectory
string FORM_Path = AppDomain.CurrentDomain.BaseDirectory + "FormData\\Login.txt";
If it is not possible to use some base path then you can give complete path.
Avoid using relative paths. Instead consider using the methods in the Path class.
Path.Combine
Path.GetDirectoryName
Step 1: get absolute path of the executable
var path = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
Step 2: get the working dir
var dir = Path.GetDirectoryName(path);
Step 3: build the new path
var filePath = Path.Combine(dir , #"FormData\Login.txt");
Related
I have to create multiple folders as e.g.
Directory.CreateDirectory("PATH\\" + _year + "filetosave.txt");
while "PATH\\" is the full path where the folder will reside, _year is the parameter and "filetosave.txt" is the file which is to be saved in respective folder.
And at run time, it should create respective folders with years in the folder name containing respective files to save.
Whereas .CreateDirectory() method only accepts string path or string path, security access as parameters.
How will we create these parameterized folders?
How can we make a check that a specified directory already exists or not?
var path = Path.Combine("PATH\\", _year.ToString(), "filettosave.txt");
Directory.CreateDirectory(path);
Directory.CreateDirectory
Creates all directories and subdirectories in the specified path unless they already exist.
Emphasis mine.
As commented, use Path.Combine when trying to build system paths:
var root = "Path";
var year = "2016";
var filename = "filetosave.txt";
var path = Path.Combine(root, year, filename);
// path = Path\2016\filetosave.txt
Directory.CreateDirectory(path);
In general, use System.IO.Path.Combine to build paths. It simplifies this task.
string dir = System.IO.Path.Combine(rootPath, _year.ToString());
Directory.CreateDirectory(dir);
string file = System.IO.Path.Combine(dir, "filetosave.txt");
FileStream fs = File.Create(file)
In my method, I'm trying to save an image in a folder in the directory of my project. I have tried just putting the direct filepath of the folder, but that gives me an error when the project runs.
Is there a built-in extension of some kind in c# that would allow me to save this image in a folder in my directory; or way to simply access my directory without drilling to where my project is saved on my computer?
private void CreateBarcode()
{
var bitmapImage = new Bitmap(500,300);
var g = Graphics.FromImage(bitmapImage);
g.Clear(Color.White);
UPCbarcode barcode = new UPCbarcode(UPCbarcode.RandomGeneratedNumber(), bitmapImage, g);
string filepath=#"images/image1.jpg";
bitmapImage.Save(filepath,System.Drawing.Imaging.ImageFormat.Jpeg);
}
You can always use the AppData folder,
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Assuming the "Image" folder is in the root directory of your Project use:
Server.MapPath("~/Image" + filename)
you can check if the file already exist at a location by :
if (!File.Exists(filePath))
{
// Your code to save the file
}
I can guess that there is similarity in the name of the image file
try putting it under a different name
like
string filepath = # "images / blabla or AI.jpg";
Use this
string filepath= Application.StartupPath + "\images\image1.jpg";
bitmapImage.Save(filepath,System.Drawing.Imaging.ImageFormat.Jpeg);
i want to create C# mass file renamer, here is my UI
i have created tes folder, inside of tes there's a file which is 1.txt.
i want to create my program to add prefix and suffix to the files, so 1.txt will become
prefix1suffix
but then i got an error
it's said file already exist though there's only one file on tes folder, which is 1.txt how do i make it work ? where's the error comes from ?
i have tried the following code
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
File.Move(f.FullName,"stackoverflow");
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
and it returns same error as the second picture above.
the following picture is tes folder, there's nothing in tes folder except 1.txt
You are calling File.Move() with a full path for your sourceFileName and a relative path for your destFileName. The relative file path is relative to the current working directory and not to the source file path. I expect that a stackoverflow file exists in the current working directory, most likely created the first time you ran this code.
your File.Move is changing them all to StackOverflow not using the prefix and suffix. If you only have one file in the directory it shouldn't be an issue. Are you sure there is only 1 file?
public static void Move(
string sourceFileName,
string destFileName
)
Looking at this answer might be the clue as you are specifying relative path for the destination file. To obtain the current working directory, see GetCurrentDirectory
The sourceFileName and destFileName arguments are permitted to specify
relative or absolute path information. Relative path information is
interpreted as relative to the current working directory.
You should change
File.Move(f.FullName,"stackoverflow");
to
string fileName = f.Name.Replace(f.Extenstion,string.Empty);
string newFileName = string.Format("{0}{1}{2}",prefix,fileName,suffix);
string newFileWithPath = Path.Combine(f.Directory,newFileName);
if (!File.Exists(newFileWithPath))
{
File.Move(f.FullName,newFileWithPath);
}
The code above will give you that error since, after the first run through, "stackoverflow" exists as a file. Make sure that you check if the destination file exists (using File.Exists) before calling File.Move.
Since your goal is renaming, I would suggest using a test folder filled with files rather than using a piecemeal approach. See if something like this helps:
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
f.MoveTo(#filepath + #"\" + prefix + f.Name.Insert(f.Name.LastIndexOf('.'),suffix));
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
on a side note using a listview to display the filenames and the changes before they're committed will help prevent unwanted changes.
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; }
}
What is the simplest way to get the directory that a file is in? I'm using this to set a working directory.
string filename = #"C:\MyDirectory\MyFile.bat";
In this example, I should get "C:\MyDirectory".
If you've definitely got an absolute path, use Path.GetDirectoryName(path).
If you might only get a relative name, use new FileInfo(path).Directory.FullName.
Note that Path and FileInfo are both found in the namespace System.IO.
System.IO.Path.GetDirectoryName(filename)
Path.GetDirectoryName(filename);
You can use System.IO.Path.GetDirectoryName(fileName), or turn the path into a FileInfo using FileInfo.Directory.
If you're doing other things with the path, the FileInfo class may have advantages.
You can use Path.GetDirectoryName and just pass in the filename.
MSDN Link
If you are working with a FileInfo object, then there is an easy way to extract a string representation of the directory's full path via the DirectoryName property.
Description of the FileInfo.DirectoryName Property via MSDN:
Gets a string representing the directory's full path.
Sample usage:
string filename = #"C:\MyDirectory\MyFile.bat";
FileInfo fileInfo = new FileInfo(filename);
string directoryFullPath = fileInfo.DirectoryName; // contains "C:\MyDirectory"
Link to the MSDN documentation.
You can get the current Application Path using:
string AssemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString();
First, you have to use System.IO namespace. Then;
string filename = #"C:\MyDirectory\MyFile.bat";
string newPath = Path.GetFullPath(fileName);
or
string newPath = Path.GetFullPath(openFileDialog1.FileName));
You can use Path.GetFullPath for most of the case.
But if you want to get the path also in the case of the file name is relatively located then you can use the below generic method:
string GetPath(string filePath)
{
return Path.GetDirectoryName(Path.GetFullPath(filePath))
}
For example:
GetPath("C:\Temp\Filename.txt") return "C:\Temp\"
GetPath("Filename.txt") return current working directory like "C:\Temp\"
In my case, I needed to find the directory name of a full path (of a directory) so I simply did:
var dirName = path.Split('\\').Last();