Create file in C# from source code - c#

I'm looking for a way to create a file from a source code (when you open a file in for example notepad it gives you some code, with that code I want to recreate the file, by stating the filetype and filename and then the code that should be in the file.
I hope you can understand my problem, it's a bit hard to explain, I'll go again...
I've got the sourcecode + filename + filetype + file description for the file that I want to create. >
Now I want C# to create a file based on that information and make it an exact copy of what that information is taken from. It should save the file, and then the file is to be openable.
Thank you in advance,
Mike

Write "code" into a file mycode.cs
string code = "code";
string filename = "mycode";
string filetype = "cs";
using (FileStream fs = File.Create(filename+"."+filetype))
{
Byte[] info = new UTF8Encoding(true).GetBytes(code);
fs.Write(info, 0, info.Length);
}

Can you just use the File.Copy method?
file.Copy("c:\temp\source.txt", "c:\temp\dest.txt");

Related

File is being used by another process while using WriteAllText in c#

I am checking file is present if specified location and if so I am replacing single quote by &#39. For this I am using WriteAllText method. For my knowledge WriteAllText will be used to Create file and write the text and close it, target file is already exists, it will be overwritten.
I don't know why I am getting System.IOException while using
var file = AppDomain.CurrentDomain.BaseDirectory + "test";
if (Directory.Exists(file))
{
string text = File.ReadAllText(file + "\\test.txt");
text = text.Replace("'", "&#39");
File.WriteAllText(file + "\\test.txt", text);
}
Note: I am using this inside Application_BeginRequest method.
Suggest me how to avoid this exception ?
Use your code like below
var file = AppDomain.CurrentDomain.BaseDirectory + "test.txt";
if (File.Exists(file))
{
string text = File.ReadAllText(file);
text = text.Replace("'", "&#39");
File.WriteAllText(file, text);
}
Hope this will solve your problem
Firstly,
You are asking on existence of Directory while using
Directory.Exists(file)
In order to check existence of File you need to use
File.Exists(file)
Secondly,
You are trying to ReadAllText from the file by passing as parameter the file concatenated with the file name again. So the file name you are passing is actually:
AppDomain.CurrentDomain.BaseDirectory + "test.txt" + "\\test.txt";
Thirdly, same comment for WriteAllText as for ReadAllText.
There are a lot of examples on the net to learn how to read and write from a file, for example:
Read from a Text File - MSDN
Write to a Text File - MSDN

Write file to project folder on any computer

I'm working on a project for a class. What I have to do is export parsed instructions to a file. Microsoft has this example which explains how to write to a file:
// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
I'm fine with that part, but is there a way to write the file to the current project's environment/location? I'd like to do that instead of hard coding a specific path (i.e. "C:\\test.txt").
Yes, just use a relative path. If you use #".\test.txt" ( btw the # just says I'm doing a string literal, it removes the need for the escape character so you could also do ".\\test.txt" and it would write to the same place) it will write the file to the current working directory which in most cases is the folder containing your program.
You can use Assembly.GetExecutingAssembly().Location to get the path of your main assembly (.exe). Do note that if that path is inside a protected folder (for example Program Files) you won't be able to write there unless the user is an administrator - don't rely on this.
Here is sample code:
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
string fileName = Path.Combine(path, "test.txt");
This question / answer shows how to get the user's profile folder where you'll have write access. Alternatively, you can use the user's My Documents folder to save files - again, you're guaranteed to have access to it. You can get that path by calling
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If you want to get the current folder location of your program use this code :
string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName; // return the application.exe current folder
string fileName = Path.Combine(path, "test.txt"); // make the full path as folder/test.text
Full code to write the data to the file :
string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
string fileName = Path.Combine(path, "test.txt");
if (!File.Exists(fileName))
{
// Create the file.
using (FileStream fs = File.Create(fileName))
{
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);
}
}

How to read and write the file using c#

I want to read the file from the local system and i want to write the file again. I am writing code like:
byte[] destination = new byte[file.ContentLength];
FileInfo fil = new FileInfo(#"d:\\Projects\\file");
if (!fil.Exists)
{
using (Stream sw = fil.OpenWrite())
{
sw.Write(destination, 0, file.ContentLength);
sw.Close();
}
}
I am able to download the file but i am not able to read the file that is downloaded. Any help is appreciated
comppath + file.FileName
First, try to avoid creating file path like this. Use System.IO.Path.Combine(comppath,file.FileName) instead.
Now debug your app and check where the downloaded file is saved. Check your save and read path are same or not. If you can write file somewhere then you can also read from the same location unless some weird rules are not applied which provide write only access to you.

How to create a folder then create a csv file inside it

I have an exe that already creates a csv file. If I save the exe in C:/EXE, then the cvs file automatically gets created in C:/EXE folder.
C# code uses StreamWriter to accomplish this:
using (TextWriter log = new StreamWriter(errorLog + errorBatchNumber.ToString("000") + ".csv", true))
{
if (errorCount == 0)
{
log.WriteLine("Error message");
}
log.WriteLine(link.StatusMessage);
log.Close();
}
What I need to add:
A folder needs to be created first where the csv file will be saved.
This folder will be created where the EXE was saved, in this example: C:/EXE
After folder and cvs file was created, it needs to be zipped thru code. (But I need to accomplish first 1 and 2)
Any ideas?
Thanks in advance guys! :)
If you know the path where the EXE will be saved then
Directory.CreateDirectory(path + folderName) to create folder
To zip items use SharpZipLib at
http://www.icsharpcode.net/opensource/sharpziplib/ or http://wiki.sharpdevelop.net/SharpZipLib_MainPage.ashx
Would be something like
DirectoryInfo di = new DirectoryInfo(#"C:\exe");
if(!di.Exists)
di.Create();
Then you can use di.FullName to get the directory to save your file into.
Syntax might be a bit off but it should be enough to get you started. You can check out the MSDN on DirectoryInfo as well.

DirectoryNotFound Exception in C#

I'm trying to save a file at path WindowsFormsApplication1\WindowsFormsApplication1\SaveFile but the following code returning me a "DirectoryNotFound" Exception with the message :
Could not find a part of the path
'D:\WindowsFormsApplication1\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\SaveFile\Hello.tx
String Path = #".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("HELLO");
}
}
Could anyone please tell me how should I save a file at my desirable folder with specifying complete path?
When you are running in the debugger, your default path is under bin\Debug. That's what "." means in your path.
Which folder do you want to save to? You'll need to specify the full path. Perhaps you'll want to pull the path from a config file. That way, the path will be able to change based on where your application is deployed.
As the error message tells you the file will be saved in the subdirectory SaveFile under bin/debug. Before you can save a file you have to create a directory with Directory.CreateDirectory("SaveFile"). It will not be automatically created.
You need to make sure the directory exists prior to creating the text file.
String Path = #".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
if (!info.Directory.Exists)
info.Directory.Create();
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("HELLO");
}
}

Categories