Creating a file from an embedded resource C# -
i new coding , have been doing lots of tutorials learn how use c# in visual studio. started working on project of own design. project generate webpages viewing photos. part of requires copy file called main.css working directory file defines style of webpage. line of code use write file executed button click , follows:
assembly.getexecutingassembly().getmanifestresourcestream("thumbscreator.main.css").copyto(new filestream(folderpath + "//main.css", filemode.create)); thumbscreator namespace name , folderpath string containing path working directory. when run code main.css file turns blank/empty until run function in program or close program. seems little inconsistent on happens closing application results in correct content turning in css file. content of file text. can suggest how can ensure css file written out after executing above line of code?
you never close file. that's why it's still open until close application (or until garbage collector collects filestream instance). long it's open cannot file other applications.
as longer answer: open file create filestream instance. since cannot referenced anywhere else collected (in case finalizer make sure file closed). happens unpredictably @ point in time after creation, or not @ all. maybe. depends on other allocations , whether gc finds time run.
generally should leave unmanaged resources (an open file unmanaged because .net doesn't know it) open long need them. easiest way in case using statement:
using (var fs = file.create(folderpath + "//main.css")) { var resource = assembly.getexecutingassembly().getmanifestresourcestream("thumbscreator.main.css"); resource.copyto(fs); } this ensure file closed leave block.
it somewhat analogous to
var fs = file.create(folderpath + "//main.css"); var resource = assembly.getexecutingassembly().getmanifestresourcestream("thumbscreator.main.css"); resource.copyto(fs); fs.close(); (note: barely, should close enough understanding.) point here using makes clear resource allocate (a filestream) , when released again (at end of block). things files, network connections , other things have dispose method, should start using (pun not intended) it.
Comments
Post a Comment