I am not a programmer, but I am a researcher and I need to modify some files.
I have a number of text files with *.mol extension located in c:\abc\ directory . I need to append line containing following text "M END" to each file in this list. I tried following in C# but without any result:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
StreamWriter sw = new StreamWriter("c:\\abc\\*.mol", true);
sw.WriteLine("M END");
sw.Close();
}
}
}
Please, suggest the solution.
Thank You!
Would you be satisfied with this oneliner that you can put in any DOS batch (.bat) file:
FOR %%I IN (c:\abc\*.mol) DO ECHO M END>>%%I
foreach (string fileName in Directory.GetFiles("directory", "*.mol"))
{
File.AppendAllText(fileName, Environment.NewLine + "M END");
}
You'll need to loop through all the files matching that pattern and write to them individually. The StreamWriter constructor you're using only supports writing to an individual file (source).
You can get a list of files using:
string[] filePaths = Directory.GetFiles("c:\\abc\\", "*.mol");
You need to iterate over the files in the directory. DirectoryInfo / FileInfo makes it easy to do this. Also, since you want to append to the end, you need to seek the stream before writing your signature at the end.
Here's a solution that works solely at that location. You will need to add recursive support to descend into subdirectories if desired.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace appender
{
class Program
{
static void AppendToFile(FileInfo fi)
{
if (!fi.Exists) { return; }
using (Stream stm = fi.OpenWrite())
{
stm.Seek(0, SeekOrigin.End);
using (StreamWriter output = new StreamWriter(stm))
{
output.WriteLine("M END");
output.Close();
}
}
}
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo("C:\\abc\\");
FileInfo[] fiItems = di.GetFiles("*.mol");
foreach (FileInfo fi in fiItems)
{
AppendToFile(fi);
}
}
}
}
Related
This question already has answers here:
Easiest way to read from and write to files
(14 answers)
Closed 2 years ago.
Below is the code I have. My issue is that the file.txt is not created at all!
I cannot find the reason. Program should create it. Could you please help me ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WriteToFile
{
class Program
{
static void Main(string[] args)
{
string line = "Please help me to write something!!";
System.IO.StreamWriter file = new System.IO.StreamWriter
(#"C:\Users\jgonc\source\repos\WriteToFile\WriteToFile\bin\Debug\file.txt");
file.Flush();
file.WriteLine(line);
file.Close();
Console.WriteLine("press a key");
Console.ReadKey();
}
}
}
//line you want to write to the document
string line = "Please help me to write something!!";
//path to my documents
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter sw = new StreamWriter(Path.Combine(docPath, "test.txt")))
{
sw.WriteLine(line);
}
Console.WriteLine("press a key");
Console.ReadKey();
Here I make use of the using keyword. This is extremely useful as any object created in the parameters will automatically be destroyed when the using segment ends which is great because it means you don't need to clutter your code with unnecessary flushes and closes.
Its also important you understand the difference between a flush & a close. Here when the using segment ends dispose is called on streamwriter which in turn calls close, which closes the stream. A flush is simply clearing the buffer.
Check that you the application has permission to write to my documents directory - here
I have changed the path to my documents as the bin folder often changes or is deleted.
Thank you for your support and hints.
I've investigate the permissions topic and it seems it was related to it.
After uninstalling my antivirus it started to work.
below is the final code, to write a couple of strings using StreamWriter.
static void Main(string[] args)
{
string[] lines = {
"Please help me to write something!",
"It's working now, it was related with my antivirus, it was somehow blocking my permissions to the folder",
"Thanks for your support and your hints!!",
};
//string path = #"C:\Users\jgonc\source\repos\WriteToFile\WriteToFile\bin\Debug\file.txt";
string path = #"file.txt";
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
System.IO.StreamWriter file = new System.IO.StreamWriter(fs, System.Text.Encoding.ASCII);
if (!File.Exists(path))
{
Console.WriteLine("file was not created");
}
else
{
using (file)
{
foreach (string line in lines) {
file.WriteLine(line);
}
}
}
fs.Close();
Console.WriteLine("Press a Key to End...");
Console.ReadKey();
}
Try :
System.IO.StreamWriter file = new System.IO.StreamWriter
(#"C:\Users\jgonc\source\repos\WriteToFile\WriteToFile\bin\Debug\file.txt", true);
true for append attribute set it false if you want to create file every time.
i am using streamwriter to write the file, however the location of the new written file is located within one of the folder with in the project folder but i would like the location to be on the document library of the computer. im using a mvc application not a console Application
Any help would be appreciate.
thank you
using (var File = new StreamWriter(System.Web.HttpContext.Current.Server.MapPath("~/OutputFileTest.csv"), false)) // true for appending the file and false to overwrite the file
{
foreach (var item in outputFile)
{
File.WriteLine(item);
}
}
From MSDN:
// Sample for the Environment.GetFolderPath method
using System;
class Sample
{
public static void Main()
{
Console.WriteLine();
Console.WriteLine("GetFolderPath: {0}",
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
}
}
/*
This example produces the following results:
*/
I am trying to read a file into a string which then I will send to another application.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("c:\text.txt"))
{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
I am getting the error:
The file could not be read:
Could not find file 'c:\users\andymarkmn\documents\visual studio 2015\Projects\FileApplication\FileApplication\bin\Debug\text.txt'.
I have tried putting the file in bin debug folders as well.
How to make sure the code works ?
EDIT: As suggested, I tried using the different ways.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
string filepath = "c:\\text.txt";
try
{
string lines = File.ReadAllText(filepath);
Console.Write(lines);
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
I still get the error:
The file could not be read:
Could not find file 'c:\text.txt'.
You have accidentally used an unwanted escape sequence in your filename string.
new StreamReader("c:\text.txt")
should be
new StreamReader(#"c:\text.txt")
Otherwise \ gets treated as an escape character, at \t is a tab character. This leaves an unexpected result, and the wrong path for the file.
# instructs the compiler to ignore any escape characters in the string.
"c:\text.txt" will not work as \ is an escape character.
use #"c:\text.txt" or "c:\\text.txt"
When StreamReader is given a non-qualified path as a parameter, it will look for the file in the application's working directory as you have done:
using (StreamReader sr = new StreamReader("c:\text.txt"))
If the file isn't located there, probably you should give StreamReader a fully qualified path:
using (StreamReader sr = new StreamReader(#"c:\text.txt"))
//or...
using (StreamReader sr = new StreamReader("c:\\text.txt"))
Try:
using (StreamReader sr = new StreamReader(#"C:\text.txt"))
If you use c:\text, C# considers that the string has a tabulador between C: and text.txt.
My requirement is to read a file location retrieve the list of .jpg & .xml files along with their timestamp and write it to a file.
I am new to C#, so far i have been able to get the file list and write the output to a file, but i am not sure how to get the time stamp of file and write it along with list.
I have added code existing code, i would need to have a timestamp for every file in list so that I can use these details for a comparison downstream.
Please advise.
Code
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
class Program
{
static void Main()
{
TextWriter tw = new StreamWriter(#"C:\test\logfile_c#.txt");
// Put all xml file names in directory into array.
string[] array1 = Directory.GetFiles(#"C:\test","*.xml");
// Put all jpg files in directory into array.
string[] array2 = Directory.GetFiles(#"C:\test", "*.jpg");
// Display all XML files and write to text file.
Console.WriteLine("--- XML Files: ---");
foreach (string name in array1)
{
Console.WriteLine(name);
tw.WriteLine(name);
Console.ReadLine();
}
// Display all JPG files and write to text file..
Console.WriteLine("--- JPG Files: ---");
foreach (string name in array2)
{
Console.WriteLine(name);
tw.WriteLine(name);
Console.ReadLine();
}
tw.Close();
}
}
Output
C:\test\chq.xml
C:\test\img_1.jpg
C:\test\img_2.jpg
Depends which timestamp you're after. You can get the creation time using:
new FileInfo(filename).CreationTime;
That'll give you a DateTime. So you can just do:
tw.WriteLine(new FileInfo(name).CreationTime.ToString());
The .ToString() is optional - you can use it to control the date/time format used in your output. There's also a modified time property you can use if you want that instead.
As you said you've just started learning I've put together this slightly modified code to show you where you can simplify some things - I've also removed reading and writing to the Console.
using System.IO;
namespace Test
{
class Program
{
static void Main(string[] args)
{
// try to name your variables in a meaningful way.
string[] xmlFiles = Directory.GetFiles(#"C:\test", "*.xml");
string[] jpgFiles = Directory.GetFiles(#"C:\test", "*.jpg");
// File.CreateText creates a new file and returns a stream writer.
// wrap it in a using statement so you don't have to worry about closing it yourself
using (var writer = File.CreateText(#"C:\test\logfile_c#.txt"))
{
FileInfo fi;
foreach (string name in xmlFiles)
{
// FileInfo instances will give you access to properties
// of the file, including the creation date and time.
fi = new FileInfo(name);
// Use an overload of WriteLine using a format string.
writer.WriteLine("file name: {0}, creation time: {1}", name, fi.CreationTime);
}
foreach (string name in jpgFiles)
{
fi = new FileInfo(name);
writer.WriteLine("file name: {0}, creation time: {1}", name, fi.CreationTime);
}
}
}
}
}
You can try writing code as below:
//Select directory
DirectoryInfo dirInfo = new DirectoryInfo("D:\\test");
//Get .xml files
FileInfo[] xmlFiles = dirInfo.GetFiles("*.xml");
//Get .jpg files
FileInfo[] jpgFiles = dirInfo.GetFiles("*.jpg");
//Merge files together for convenience
List<FileInfo> allFiles = new List<FileInfo>();
allFiles.InsertRange(allFiles.Count, xmlFiles);
allFiles.InsertRange(allFiles.Count, jpgFiles);
//Loop through all files and write their name and creation time to text file
using (StreamWriter writer = new StreamWriter("D:\\test\\test.txt"))
{
foreach (FileInfo currentFile in allFiles)
{
//Format string in desired format
string info = string.Format("Name: {0} Creation time: {1}", currentFile.Name, currentFile.CreationTime);
writer.WriteLine(info);
}
}
Im trying to decompress a bz2 file via code using the ICSharpCode.SharpZipLib.
It seems no matter where I make my file, even though I have FULL ACCESS control over it, I keep getting this Exception. Any help greatly appreciated.
using System;
using System.IO;
using ICSharpCode.SharpZipLib.BZip2;
namespace decompressor
{
class MainClass
{
public static void Main(string[] args)
{
string filePath = "C:\\FreeBase\\opinions.tsv.bz2";
string decompressPath = "C:\\Users\\mike\\Desktop\\Decompressed";
Console.WriteLine("Decompressing {0} to {1}", file, path);
BZip2.Decompress(File.OpenRead(filePath),File.OpenWrite(decompressPath), true);
}
}
}
Your code can have no access to create new paths at your desktop.
Check the permissions for the "C:\\Users\\mike\\Desktop\\Decompressed".
Maybe, you should write so:
string decompressPath = "C:\\Users\\mike\\Desktop\\Decompressed\\opinions.tsv";