Create a .txt file if doesn't exist with user inputted data - c#

Is there any way to create a text file using a name that comes from data entered in a form?
string path = #"E:\AppServ\**Example**.txt";
if (!File.Exists(path))
{
File.Create(path);
}
**Example** being the part taken from user inputted data.
Similar to this Console.Writeline("{0}", userData);

Here is an example of how to store files to the logged in users My Documents folder on windows.
You can modify the AppendUserFile function to support other file modes. This version will open the file for Appending if it exists, or create it if it doesn't exist.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
AppendUserFile("example.txt", tw =>
{
tw.WriteLine("I am some new text!");
});
Console.ReadKey(true);
}
private static bool AppendUserFile(string fileName, Action<TextWriter> writer)
{
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string filePath = Path.Combine(path, fileName);
FileStream fs = null;
if (File.Exists(filePath))
fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read);
else
fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read);
using (fs)
{
try
{
TextWriter tw = (TextWriter)new StreamWriter(fs);
writer(tw);
tw.Flush();
return true;
}
catch
{
return false;
}
}
}
}
}

Related

'System.IO.FileNotFoundException' in compressor/decompressor .Net Core console program

I'm making an compressor / decompressor console program in Visual Studio 2017 and I want to get the filepath by dragging the input file to the console (.txt).
i'm getting the right path for inputStream for Compress() but outPutStream fails and cant find the filepath (FileMode.OpenOrCreate!?!), even if the path is hardcoded.
Program executes correctly if both variables are hardcoded, but i can't understand why System.IO.FileNotFoundException is thrown by getting input file from dragging the file to console and have the output file hardcoded.
....
string outPutFileName = #"C:\bla\bla\bla\bla\gergrgr.gzip";
public static void Compress(string inPath)
{
using (FileStream inputStream = new FileStream(inPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (FileStream outputStream = new FileStream(outPutFileName, FileMode.OpenOrCreate, FileAccess.Write))
{
using (GZipStream gzip = new GZipStream(outputStream, CompressionMode.Compress))
{
inputStream.CopyTo(gzip);
}
}
}
}
static void Main(string[] args)
{
string outPutFileName = #"C:\bla\bla\bla\bla\gergrgr.gzip";
//dummy var, cant find a better way to add '#' to variable set by console.readline
string filePath = #"test";
// info info info....
Console.WriteLine("Drag in txt file");
// Takes the path from dragged in file
string idk = Console.ReadLine();
// instead of of a loop to escape "/", just replace text in filePath
filePath = filePath.Replace("test", idk);
Compress(filePath);
}
I think the problem is actually that your app doesn't have permissions to write to the specified output location. Check the docs for FileMode.OpenOrCreate
If the file access is FileAccess.Write, Write permission is required.
The below works for me:
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApp1
{
internal class Program
{
private static readonly string outPutFileName = #"C:<my desktop directory>\gergrgr.gzip";
public static void Compress(string inPath)
{
using (var inputStream = new FileStream(inPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (var outputStream = new FileStream(outPutFileName, FileMode.OpenOrCreate, FileAccess.Write))
{
using (var gzip = new GZipStream(outputStream, CompressionMode.Compress))
{
inputStream.CopyTo(gzip);
}
}
}
}
private static void Main(string[] args)
{
// info info info....
Console.WriteLine("Drag in txt file");
// Takes the path from dragged in file
var filePath = Console.ReadLine();
if (!string.IsNullOrEmpty(filePath))
{
Compress(filePath.Trim('\\', '"'));
}
}
}
}

Move position in FileStream (C#)

I have a txt file like this
#header1
#header2
#header3
....
#headerN
ID Value Pvalue
a 0.1 0.002
b 0.2 0.002
...
My code will try to parse
FileStream fs = new FileStream(file, FileMode.Open, FileMode.Read);
......
Table t = Table.Load(fs);
what I want is to make the start position of the Stream right before "ID", so I can feed the stream to the code and make a new table. But I am not sure what is the correct way to do it.
Thanks in advance
Ideally, you should convert Table.Load to take an IEnumerable<string> or at least a StreamReader, not a raw Stream.
If this is not an option, you can read the whole file into memory, skip its header, and write the result into MemoryStream:
MemoryStream stream = new MemoryStream();
using (var writer = new StreamWriter(stream, Encoding.UTF8);
foreach (var line in File.ReadLines(fileName).SkipWhile(s => s.StartsWith("#"))) {
writer.WriteLine(line);
}
}
stream.Position = 0;
Table t = Table.Load(stream);
Try this code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication57
{
class Program
{
const string file = "";
static void Main(string[] args)
{
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fs);
string inputline = "";
State state = State.FIND_HEADER;
while((inputline = reader.ReadLine()) != null)
{
switch (state)
{
case State.FIND_HEADER:
if (inputline.StartsWith("#header"))
{
state = State.READ_TABLE;
}
break;
case State.READ_TABLE:
Table t = Table.Load(fs);
break;
}
}
}
enum State
{
FIND_HEADER,
READ_TABLE
}
}
}

How would I write this to a csv file in c#?

I hope someone can help me. I am a beginner at c# and programming in general and I'm trying to complete this program. Basically it looks in an XML file, grabs all of the occurrences of a specific tag and is supposed to write the File Names plus whatever is between any instances of these two tags. So far I've tried TextWriter, StreamWriter, FileStream and some others and nothing doing what I want. I realise this may be a stupid question but I'm a super noob and need help for my particular case. My code is as follows.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var files = from file in Directory.GetFiles("W:\\SRC\\hDefMl\\1.0\\Instrument_Files")
orderby file
ascending
select file;
StringBuilder sb_report = new StringBuilder();
string delimiter = ",";
sb_report.AppendLine(string.Join(delimiter, "Module", "Generator(s)"));
foreach (var file in files)
{
string filename = Path.GetFileNameWithoutExtension(file);
Console.WriteLine("The HDefML file for {0} contains these EEPROM Generators:", filename);
XDocument hdefml = XDocument.Load(file);
var GeneratorNames = from b in hdefml.Descendants("Generators")
select new
{
name = (string)b.Element("GeneratorName")
};
string description;
foreach (var generator in GeneratorNames)
{
Console.WriteLine(" GeneratorName is: {0}", generator.name);
sb_report.AppendLine(string.Join(delimiter, filename,
generator.name));
}
}
}
You should be able to just do something like this, if the string you have built with your string builder is formatted correctly.
static void WriteToCSV(string str, string path)
{
using (Stream stream = File.Create(path))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(str);
}
}
try{
FileStream FS;
StreamWriter SW;
using (FS = new FileStream("HardCodedFileName.csv", FileMode.Append))
{
using (SW = new StreamWriter(FS))
{
foreach (var generator in GeneratorNames)
{
SW.WriteLine(string.Join(delimiter, filename,
generator.name));
}
}
}
}
catch (Exception e){
Console.Writeline(e.ToString());
}

Asp.net FileStream Create throws error if file doesn't exist

I have a file path that might exist or might not exist.
I want to create / override the file, and i have this code:
string filePath = GetFilePath();
using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
xDoc.Save(file);
}
When i call using (FileStream file ...) and the file doesn't exist, it throws an Could not find a part of the path... error.
I am doing something wrong? shouldn't it create the file if doesn't exist?
FileStream can't create intermediate directories that don't exist. This question should help you.
FileMode.OpenOrCreate creates a file if it doesn't exist. If you also need to create the directory:
bool dirExists = System.IO.Directory.Exists(dir);
if(!dirExists)
System.IO.Directory.CreateDirectory(dir);
using(var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
}
OpenOrCreate
Specifies that the operating system should open a file if it exists;
otherwise, a new file should be created.
try this:
void OpenOrCreateFile()
{
try
{
string filePath = GetFilePath();
EnsureFolder(filePath); //if directory not exist create it
using(var fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
//your code
}
}
catch(Exception ex)
{
//handle exception
}
}
void EnsureFolder(string path)
{
string directoryName = Path.GetDirectoryName(path);
if ((directoryName.Length > 0) && (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
}
You can use StreamWriter has a boolean parameter append to overwrite the file it contents exits
http://msdn.microsoft.com/en-IN/library/36b035cb.aspx
public StreamWriter(
string path,
bool append
)
You can use the below given code
using System;
using System.IO;
using System.Text;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string fileName = "test.txt";
string textToAdd = "Example text in file";
using (StreamWriter writer = new StreamWriter(fileName, false))
{
writer.Write(textToAdd);
}
}
}
}

C# - How to read a text file from GZip

Here is my problem, i'm trying to make minecraft classic server and i'm using text system to make allow list for each map, problem is text system makes a file for each map and we got around 15k maps in total, so if 1k of players add allow list to their maps, it would be hard to upload / move server to another host. i want to make a zip file in main folder of my software and add each text file to it and also making it readable with system, i want to know how to read a file from GZip, and how to compress files also.
Thanks
Here is my very easy working code. No temporary file
using (FileStream reader = File.OpenRead(filePath))
using (GZipStream zip = new GZipStream(reader, CompressionMode.Decompress, true))
using (StreamReader unzip = new StreamReader(zip))
while(!unzip.EndOfStream)
ReadLine(unzip.ReadLine());
If you want to avoid creating temporary files, you can use this:
using (Stream fileStream = File.OpenRead(filePath),
zippedStream = new GZipStream(fileStream, CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(zippedStream))
{
// work with reader
}
}
Details on how to use GZip to compress and decompress. After decompression, you can use the StreamReader() class to read the contents of the file (.NET 4.0).
using System;
using System.IO;
using System.IO.Compression;
namespace zip
{
public class Program
{
public static void Main()
{
string directoryPath = #"c:\users\public\reports";
DirectoryInfo directorySelected = new DirectoryInfo(directoryPath);
foreach (FileInfo fileToCompress in directorySelected.GetFiles())
{
Compress(fileToCompress);
}
foreach (FileInfo fileToDecompress in directorySelected.GetFiles("*.gz"))
{
Decompress(fileToDecompress);
}
}
public static void Compress(FileInfo fileToCompress)
{
using (FileStream originalFileStream = fileToCompress.OpenRead())
{
if ((File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
{
using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fileToCompress.Name, fileToCompress.Length.ToString(), compressedFileStream.Length.ToString());
}
}
}
}
}
public static void Decompress(FileInfo fileToDecompress)
{
using (FileStream originalFileStream = fileToDecompress.OpenRead())
{
string currentFileName = fileToDecompress.FullName;
string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
Console.WriteLine("Decompressed: {0}", fileToDecompress.Name);
}
}
}
}
}
}
Source

Categories

Resources