by drewrv · 14y ago · 0 comments
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None))
{
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);
}Ruby has similar concept when you open a file and pass in a block to operate on the File object.
I'm pretty sure the author is just excited about the language and failed to recognize that this pattern is everywhere in different programming languages.
with_under do_something() as f:
...
translated to f = do_something()
...
f.undo_something()
With do_something automatically matched to undo_something. new FileEx (SOME_PATH, () => ConsoleEx.ReadLine (), () => ConsoleEx.CurrentLine != "QUIT").WriteAll ();
is equivalent to using (var file = new File(SOME_PATH))
{
string line = null;
try
{
while((line = Console.ReadLine) != "QUIT")
{
file.WriteLine(line);
}
}
catch (Exception ex)
{
throw;
}
finally
{
sw.Close();
}
}It doesn't seem to be part of the framework though? Homegrown and _you_ expand it to something that is equivalent to the second code snippet?
Another one that I use a lot [2]:
SqlCommandEx sql = "select * from person";
foreach (dynamic result in sql)
{
var full_name = result.first_name + " " + result.last_name;
DateTime dob = result.dob;
//do other stuff
} //connection automatically disposed.
[1] Relevant source: http://pastebin.com/LwHD8MHc[2] https://github.com/noblethrasher/Prelude/blob/master/SQL.cs
System.IO.File.AppendAllText(path, "This is some text in the file.");
Also, why are you writing text to binary file instead of just writing the text as a text file?