Home   -   Computerkurs   Demos   Editpointstatic   Folderwatcher   Gipsydrive   Licenses   Shrinkseries   V4   More...  

All   Asm   Bas   C   C++   C#   Couch   CSS   HTML   Java   JS   Lisp   OPAL   PHP   Perl   PS   Py   SQL   Win  

Arrays   Files   Processes   RegEx   AccessIE   Linq   WindowsServices   SimpleGuiAccess   WpfTreeView  

Previous page Home chapter Next page

Downtown Programmer's Corner   -   Demos   -   C#

Files

Some snippets around file handling in C#.

Get the filename of current program.

Get the filename of the currently running program:

   // (# 20111008.1301)
   // This will yield e.g. "G:\work\downtown\csdemos\trunk\ieautomat\ieautomat\bin\Debug\ieautomat.exe",
   // it will be the same, if the line is inside the calling program or inside a dll which is called by the program.
   string sThisfile = System.Reflection.Assembly.GetEntryAssembly().Location;

   // (# 20111008.1302)
   // This will yield e.g. "G:\work\downtown\csdemos\trunk\ieautomat\ieautomat\bin\Debug".
   // It may touch the filesystem and throw an exception if you don't have appropriate permission. [todo: verify statement]
   DirectoryInfo dinfo = new DirectoryInfo(sThisfile);
   string sThispath = dinfo.Parent.FullName;

Textfiles

Read textfile to array: (# 20111007.1231, 20111007.1232).

   string sFile = "C:\testfile.txt";
   string[] a = {};
   if (System.IO.File.Exists(sFile)
   {
      a = System.IO.File.ReadAllLines(sFile);
   }

Write array to textfile: (# 20111007.1234).

   // ..
   string[] aLines = {"Line one.", "Line two.", "Line three."};
   System.IO.File.WriteAllLines(@"C:\tmp\output.txt", aLines);

Append lines to textfile: (# 20111007.1234).

   (# 20111007.1521).
   using (System.IO.StreamWriter file = new System.IO.StreamWriter(sInifile, true))
   {
      file.WriteLine(s);
      file.WriteLine("");
   }  

.

.

.

Links

MSDN   File Class   about the File class, e.g. to copy files ... (# 20111115.1241). Reference
MSDN How to: Write to a Text File (C# Programming Guide). Simple recipe. (# 20111007.1234) Recipe
MSDN How to: Read From a Text File (C# Programming Guide). Simple recipe. (# 20111007.1232) Recipe
MSDN File.Exists Method simple recipe (# 20111007.1231). Recipe

.

Imprint : www.trilo.de/imprint.html