File is always named with the Path - c#

My File is always named like the path and my additional informations i want to have in the Filename but why is it like that?
The Path should be the chosen folder and i want to create a folder then, how can i add a folder than and say + that folder path?
The file is also always created 1 layer above the one i want. For example: C:\Test but the file is saved then in C:\ instead of C:\Test.
public static string path= string.Empty;
string fileName = DateTime.Now.ToString("yyyy.MM.dd") + "test.txt";
try
{
FileStream fs = new FileStream(path + fileName, FileMode.CreateNew, FileAccess.ReadWrite);
StreamWriter sw= new StreamWriter(fs);
sw.WriteLine("Test and so on ..");
}
catch(Exception ex) { }

Rather than using string concatenation, use Path.Combine. Aside from anything else, that will be portable if you ever want to use Mono, too.
Oh, and there are simpler ways to create a text file too:
using (var writer = File.CreateText(Path.Combine(path, fileName))
{
writer.WriteLine(...);
}
Finally, I'd strongly advise using - instead of . in your filename, so that anything which looks at the first . and expects the rest to be an extension doesn't get confused:
string fileName = DateTime.ToString("yyyy-MM-dd") + "-test.txt";

Related

I'm getting "The process cannot access the file because it is being used by another process" error. Any ideas?

So, I created a file and a txt file into the AppData, and I want to overwrite the txt. But when I try to do it, it keeps giving me that error. Any ideas?
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string setuppath = (path + "\\");
string nsetuppath = (setuppath + "newx" + "\\");
Directory.CreateDirectory(nsetuppath);
string hedef2 = (nsetuppath + "commands.txt");
File.Create(hedef2);
StreamWriter sw = new StreamWriter(hedef2); ----> This is where the error appears.
sw.WriteLine("Testtest");
Just use the using statement when using streams. The using statement automatically calls Dispose on the object when the code that is using it has completed.
//path to the file you want to create
string path = #"C:\code\Test.txt";
// Create the file, or overwrite if the file exists.
using (FileStream fs = File.Create(path))
{
byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
There are many ways of manipulate streams, keep it simple depending on your needs

Change former path to custom path keeping the filename and create a file using stream writer in c#

I am creating multiple files using StreamWriter, I want these files to be created in a specific directory
StreamWriter w = new StreamWriter(File.Create(name + ".txt"));
w.WriteLine(name);
w.Close();
here name is variable that is used as file name and also to be written in that file, but my problem is I want this file to be created in specific directory.
Use Path.Combine
Path.Combine uses the Path.PathSeparator and it checks whether the first path has already a separator at the end so it will not duplicate the separators. Additionally, it checks whether the path elements to combine have invalid chars.
Quoted from this SO post
Also it would be fruitful to check if you name variable contains invalid characters for a filename.
You may first remove invalid characters from name variable using Path.GetInvalidFileNameChars method :
var invalidChars = Path.GetInvalidFileNameChars();
string invalidCharsRemoved = new string(name
.Where(x => !invalidChars.Contains(x))
.ToArray());
Quoted from this SO post
string directory = "c:\\temp";
Instead of
File.Create(name + ".txt")
Use
string filename = invalidCharsRemoved + ".txt"
File.Create(Path.Combine(directory , filename ))
You can include the path too:
string path = "C:\\SomeFolder\\";
File.Create( path + name + ".txt");
Or Use Path.Combine like:
File.Create( Path.Combine(path, name + ".txt") );
FileStream fileStream = null;
StreamWriter writer = null;
try
{
string folderPath = #"D:\SpecificDirecory\";
string path = Path.Combine(folderPath , "fileName.txt");
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
fileStream = new FileStream(#path, FileMode.Create);
writer = new StreamWriter(fileStream);
writer.Write(fileBuilder.ToString());
}
catch (Exception ex)
{
throw ex;
}
finally
{
writer.Close();
fileStream.Close();
}
name contains some thing like #"U:\TDScripts\acchf122_0023"
ok according to the new information from your comment you need actually to get rid of the old path and directory.
You can use the Path.GetFileNameWithoutExtension method to achieve that. After that you can use Path.Combine to create your own path.
Here is an example to demonstrate this:
string myDirectory = #"C:\temp";
string oldPathWithName = #"U:\TDScripts\acchf122_0023";
string onlyFileName = Path.GetFileNameWithoutExtension(oldPathWithName);
string myNewPath = Path.Combine(myDirectory, onlyFileName + ".txt");
Console.WriteLine(myNewPath);
I hope this solves your problem.
You can declare a path for your directory like this :
string path = #"c:\folder\....";
Then with the following command:
File.Create( path + name + ".txt");
You will get what you want

File is in use by another process with SteamWriter [duplicate]

I'm trying to detect if a file exists at runtime, if not, create it. However I'm getting this error when I try to write to it:
The process cannot access the file 'myfile.ext' because it is being used by another process.
string filePath = string.Format(#"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre);
if (!File.Exists(filePath))
{
File.Create(filePath);
}
using (StreamWriter sw = File.AppendText(filePath))
{
//write my text
}
Any ideas on how to fix it?
File.Create(FilePath).Close();
File.WriteAllText(FileText);
I want to update this answer to say that this is not really the most efficient way to write all text. You should only use this code if you need something quick and dirty.
I was a young programmer when I answered this question, and back then I thought I was some kind of genius for coming up with this answer.
The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:
string filePath = #"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
//write to the file
}
The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.
When creating a text file you can use the following code:
System.IO.File.WriteAllText("c:\test.txt", "all of your content here");
Using the code from your comment. The file(stream) you created must be closed. File.Create return the filestream to the just created file.:
string filePath = "filepath here";
if (!System.IO.File.Exists(filePath))
{
System.IO.FileStream f = System.IO.File.Create(filePath);
f.Close();
}
using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
{
//write my text
}
FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
fs.Close();
File.Create returns a FileStream. You need to close that when you have written to the file:
using (FileStream fs = File.Create(path, 1024))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can use using for automatically closing the file.
I updated your question with the code snippet. After proper indenting, it is immediately clear what the problem is: you use File.Create() but don't close the FileStream that it returns.
Doing it that way is unnecessary, StreamWriter already allows appending to an existing file and creating a new file if it doesn't yet exist. Like this:
string filePath = string.Format(#"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre);
using (StreamWriter sw = new StreamWriter(filePath, true)) {
//write my text
}
Which uses this StreamWriter constructor.
I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")", just add .Dispose() to it.
File.Create("filename").Dispose();
This way it creates and closes the file for the next process to use it.
This question has already been answered, but here is a real world solution that
checks if the directory exists and adds a number to the end if the text file
exists. I use this for creating daily log files on a Windows service I wrote. I
hope this helps someone.
// How to create a log file with a sortable date and add numbering to it if it already exists.
public void CreateLogFile()
{
// filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
var filePath = "C:\\Logs";
// Append a backslash if one is not present at the end of the file path.
if (!filePath.EndsWith("\\"))
{
filePath += "\\";
}
// Create the path if it doesn't exist.
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
// Create the file name with a calendar sortable date on the end.
var now = DateTime.Now;
filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);
// Check if the file that is about to be created already exists. If so, append a number to the end.
if (File.Exists(filePath))
{
var counter = 1;
filePath = filePath.Replace(".txt", " (" + counter + ").txt");
while (File.Exists(filePath))
{
filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
counter++;
}
}
// Note that after the file is created, the file stream is still open. It needs to be closed
// once it is created if other methods need to access it.
using (var file = File.Create(filePath))
{
file.Close();
}
}
I think I know the reason for this exception. You might be running this code snippet in multiple threads.
you can just use using keyword around File.Create(path) to finalize the process
using(File.Create(path));
Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :
using (FileStream fs= new FileStream(#"File.txt",FileMode.Create,FileAccess.ReadWrite))
{
fs.close();
}
using (StreamWriter sw = new StreamWriter(#"File.txt"))
{
sw.WriteLine("bla bla bla");
sw.Close();
}

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.

File being used by another process after using File.Create()

I'm trying to detect if a file exists at runtime, if not, create it. However I'm getting this error when I try to write to it:
The process cannot access the file 'myfile.ext' because it is being used by another process.
string filePath = string.Format(#"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre);
if (!File.Exists(filePath))
{
File.Create(filePath);
}
using (StreamWriter sw = File.AppendText(filePath))
{
//write my text
}
Any ideas on how to fix it?
File.Create(FilePath).Close();
File.WriteAllText(FileText);
I want to update this answer to say that this is not really the most efficient way to write all text. You should only use this code if you need something quick and dirty.
I was a young programmer when I answered this question, and back then I thought I was some kind of genius for coming up with this answer.
The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:
string filePath = #"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
//write to the file
}
The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.
When creating a text file you can use the following code:
System.IO.File.WriteAllText("c:\test.txt", "all of your content here");
Using the code from your comment. The file(stream) you created must be closed. File.Create return the filestream to the just created file.:
string filePath = "filepath here";
if (!System.IO.File.Exists(filePath))
{
System.IO.FileStream f = System.IO.File.Create(filePath);
f.Close();
}
using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
{
//write my text
}
FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
fs.Close();
File.Create returns a FileStream. You need to close that when you have written to the file:
using (FileStream fs = File.Create(path, 1024))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can use using for automatically closing the file.
I updated your question with the code snippet. After proper indenting, it is immediately clear what the problem is: you use File.Create() but don't close the FileStream that it returns.
Doing it that way is unnecessary, StreamWriter already allows appending to an existing file and creating a new file if it doesn't yet exist. Like this:
string filePath = string.Format(#"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre);
using (StreamWriter sw = new StreamWriter(filePath, true)) {
//write my text
}
Which uses this StreamWriter constructor.
I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")", just add .Dispose() to it.
File.Create("filename").Dispose();
This way it creates and closes the file for the next process to use it.
This question has already been answered, but here is a real world solution that
checks if the directory exists and adds a number to the end if the text file
exists. I use this for creating daily log files on a Windows service I wrote. I
hope this helps someone.
// How to create a log file with a sortable date and add numbering to it if it already exists.
public void CreateLogFile()
{
// filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
var filePath = "C:\\Logs";
// Append a backslash if one is not present at the end of the file path.
if (!filePath.EndsWith("\\"))
{
filePath += "\\";
}
// Create the path if it doesn't exist.
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
// Create the file name with a calendar sortable date on the end.
var now = DateTime.Now;
filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);
// Check if the file that is about to be created already exists. If so, append a number to the end.
if (File.Exists(filePath))
{
var counter = 1;
filePath = filePath.Replace(".txt", " (" + counter + ").txt");
while (File.Exists(filePath))
{
filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
counter++;
}
}
// Note that after the file is created, the file stream is still open. It needs to be closed
// once it is created if other methods need to access it.
using (var file = File.Create(filePath))
{
file.Close();
}
}
I think I know the reason for this exception. You might be running this code snippet in multiple threads.
you can just use using keyword around File.Create(path) to finalize the process
using(File.Create(path));
Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :
using (FileStream fs= new FileStream(#"File.txt",FileMode.Create,FileAccess.ReadWrite))
{
fs.close();
}
using (StreamWriter sw = new StreamWriter(#"File.txt"))
{
sw.WriteLine("bla bla bla");
sw.Close();
}

Categories

Resources