<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Listener&#039;s Blog</title>
	<atom:link href="http://www.listener.com.ba/thepage/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.listener.com.ba/thepage</link>
	<description></description>
	<lastBuildDate>Sat, 07 Apr 2012 11:01:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Unity3d PointCache pc2 file Reader</title>
		<link>http://www.listener.com.ba/thepage/2012/04/02/unity3d-pointcache-pc2-file-reader/</link>
		<comments>http://www.listener.com.ba/thepage/2012/04/02/unity3d-pointcache-pc2-file-reader/#comments</comments>
		<pubDate>Mon, 02 Apr 2012 20:23:42 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.listener.com.ba/thepage/?p=122</guid>
		<description><![CDATA[<p>Because Unity does not have native support for vertex animation i have created this point cache reader, it reads point cache files in pc2 format  that is supported by major 3d software packages.</p> <p>Here is the short video on how it works, it is a cloth from blender cached to pc2 file and transfered to [...]]]></description>
			<content:encoded><![CDATA[<p>Because Unity does not have native support for vertex animation i have created this point cache reader, it reads point cache files in pc2 format  that is supported by major 3d software packages.</p>
<p>Here is the short video on how it works, it is a cloth from blender cached to pc2 file and transfered to Unity where pc2 reader reads file and plays animation, fps is fully adjustable.</p>

<object width="640" height="360">
<param name="allowfullscreen" value="true" />
<param name="allowscriptaccess" value="always" />
<param name="movie" value="http://www.youtube.com/v/vzNvziniaxU&autoplay=0&loop=0&rel=0" />
<param name="wmode" value="transparent">
<embed src="http://www.youtube.com/v/vzNvziniaxU&autoplay=0&loop=0&rel=0" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" allowscriptaccess="always" width="640" height="360">
</embed>
</object>


<p><span id="more-122"></span></p>
<p>Also here is code, just make new C# script in Unity, copy and paste this code and attach it to your object then in inspector give it path to pc2 file (presumably in added to unity project) and set fps.</p>
<p>&nbsp;</p>
<pre class="crayon-plain-tag"><code>//
//POINT CACHE READER
//
//Created By: Dejan Omasta
//email: list3ner@gmail.com
//
//=================================================
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class PointCacheReader : MonoBehaviour
{
//
//POINT CACHE Vs
//
public string filePath;

struct PointCacheFile
{
public char[] signature;
public int fileVersion;
public int numPoints;
public float startFrame;
public float sampleRate;
public int numSamples;
public List vertexCoords;
}

PointCacheFile pcFile;
bool fileParsed = false;
//
//VERTEX POS Vs
//
public float fps = 24.0f;
Mesh mesh;
Vector3[] vertices;
int counter = 0;
int curFrame = 0;
float tempTime = 0.0f;
float timeMeasure = 0.0f;

// Use this for initialization
void Start ()
{
pcFile = new PointCacheFile();
ParsePCFile();

timeMeasure = 1 / fps;
mesh = this.GetComponent().mesh;
vertices = mesh.vertices;
tempTime = Time.time;
}

// Update is called once per frame
void Update ()
{

}

void FixedUpdate()
{
if(Time.time &amp;gt; tempTime + timeMeasure)
{
if (fileParsed)
{

for (int x = 0; x &amp;lt; vertices.Length; x++)
{
vertices[x] = pcFile.vertexCoords[counter];
counter++;
}
mesh.vertices = vertices;
mesh.RecalculateBounds();
mesh.RecalculateNormals();
curFrame++;
if (curFrame == pcFile.numSamples)
{
curFrame = 0;
counter = 0;
}
}
tempTime = Time.time;
}
}

void ParsePCFile()
{
FileStream fs = new FileStream(filePath, FileMode.Open);
BinaryReader binReader = new BinaryReader(fs);
//
//SIGNATURE
//
pcFile.signature = new char[12];
pcFile.signature = binReader.ReadChars(12);
//
//FILE VERSION
//
pcFile.fileVersion = binReader.ReadInt32();
//
//NUMBER OF POINTS
//
pcFile.numPoints = binReader.ReadInt32();
//
//START FRAME
//
pcFile.startFrame = binReader.ReadSingle();
//
//SAMPLE RATE
//
pcFile.sampleRate = binReader.ReadSingle();
//
//NUMBER OF SAMPLES
//
pcFile.numSamples = binReader.ReadInt32();
//
//GET VERTEX COORDS
//
pcFile.vertexCoords = new List();
for (int i = 0; i &amp;lt; pcFile.numSamples; i++)
{
for (int x = 0; x &amp;lt; pcFile.numPoints; x++)
{
Vector3 vPos = new Vector3();
vPos.x = binReader.ReadSingle();
vPos.y = binReader.ReadSingle();
vPos.z = binReader.ReadSingle();
pcFile.vertexCoords.Add(vPos);
}
}
fileParsed = true;
}
}</code></pre>
<p>I made update to the code and workflow so it supports playing point cache files on android also (i don&#8217;t own iPhone so i could not do tests there but i think it should work also), the procedure is a bit diferent.</p>
<p>1. When you make your pc2 file change its extension in to *.bytes<br />
2. Create folder Resources in your project<br />
3. Drag &#8216;n drop your file with changed extension in to Resources folder</p>
<p>That&#8217;s it, only thing you need to do is when you attach this script to your mesh just drag and drop your file from Resources folder to Cache File field in inspector, like you would assign any public variable (Transform, Material etc&#8230;)</p>
<p>And here is the code for it:</p>
<pre class="crayon-plain-tag"><code>//
//POINT CACHE READER (Works on Android, probably iPhone too:))
//
//Created By: Dejan Omasta
//email: list3ner@gmail.com
//
//=================================================

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
public class PointCacheAndReader : MonoBehaviour
{
//
//POINT CACHE Vs
//
public TextAsset cacheFile;
struct PointCacheFile;
{
public char[] signature;
public int fileVersion;
public int numPoints;
public float startFrame;
public float sampleRate;
public int numSamples;
public List vertexCoords;
}

PointCacheFile pcFile;
bool fileParsed = false;

//
//VERTEX POS Vs
//
public float fps = 24.0f;
Mesh mesh;
Vector3[] vertices;
int counter = 0;
int curFrame = 0;
float tempTime = 0.0f;
float timeMeasure = 0.0f;

// Use this for initialization
void Start ()
{
pcFile = new PointCacheFile();
Debug.Log(&quot;ZETZ - Calling ParsePCFile&quot;);
ParsePCFile();
timeMeasure = 1 / fps;
mesh = this.GetComponent().mesh;
vertices = mesh.vertices;
tempTime = Time.time;
}

// Update is called once per frame
void Update ()
{

}

void FixedUpdate()
{
if(Time.time &amp;gt; tempTime + timeMeasure)
{
if (fileParsed)
{
for (int x = 0; x &amp;lt; vertices.Length; x++)
{
vertices[x] = pcFile.vertexCoords[counter];
counter++;
}
mesh.vertices = vertices;
mesh.RecalculateBounds();
mesh.RecalculateNormals();
curFrame++;
if (curFrame == pcFile.numSamples)
{
curFrame = 0;
counter = 0;
}
}
tempTime = Time.time;
}
}

void ParsePCFile()
{
MemoryStream ms = new MemoryStream(cacheFile.bytes);
BinaryReader binReader = new BinaryReader(ms);
//
//SIGNATURE
//
pcFile.signature = new char[12];
pcFile.signature = binReader.ReadChars(12);
//
//FILE VERSION
//
pcFile.fileVersion = binReader.ReadInt32();
//
//NUMBER OF POINTS
//
pcFile.numPoints = binReader.ReadInt32();
//
//START FRAME
//
pcFile.startFrame = binReader.ReadSingle();
//
//SAMPLE RATE
//
pcFile.sampleRate = binReader.ReadSingle();
//
//NUMBER OF SAMPLES
//
pcFile.numSamples = binReader.ReadInt32();
//
//GET VERTEX COORDS
//
pcFile.vertexCoords = new List();
for (int i = 0; i &amp;lt; pcFile.numSamples; i++)
{
for (int x = 0; x &amp;lt; pcFile.numPoints; x++)
{
Vector3 vPos = new Vector3();
vPos.x = binReader.ReadSingle();
vPos.y = binReader.ReadSingle();
vPos.z = binReader.ReadSingle();
pcFile.vertexCoords.Add(vPos);
}
}
fileParsed = true;
}
}</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.listener.com.ba/thepage/2012/04/02/unity3d-pointcache-pc2-file-reader/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python snapshot maker for Nuke</title>
		<link>http://www.listener.com.ba/thepage/2012/02/22/97/</link>
		<comments>http://www.listener.com.ba/thepage/2012/02/22/97/#comments</comments>
		<pubDate>Wed, 22 Feb 2012 18:58:41 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Nuke]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Plugins]]></category>

		<guid isPermaLink="false">http://www.listener.com.ba/thepage/?p=97</guid>
		<description><![CDATA[<p>This is a small tool written in Python that will make snapshot of your current work in Nuke and create new read node and set it as second input to your active Viewer node, so you can use mixing A and B inputs in order to see differences that have been made.</p> <p><br /> This [...]]]></description>
			<content:encoded><![CDATA[<p>This is a small tool written in Python that will make snapshot of your current work in Nuke and create new read node and set it as second input to your active Viewer node, so you can use mixing A and B inputs in order to see differences that have been made.</p>
<p><span id="more-97"></span><br />
This was written when friend from work asked me can we somehow implement some function in Nuke like After Effects has with snapshot where you can save image at certain point to compare it with later work, this is what i came up a quick fix in Nuke it was really fast, a bit of it i found on the foundry forums about getting screenshot i was thinking to get image from disk cache if possible but stumbled on this solution that was my second choice but it works. Hope you will find it helpful.</p>
<pre class="crayon-plain-tag"><code>import nuke

import getpass

import os

active = False

def renderCurrentFrame(index):

viewer = nuke.activeViewer()

actInput = nuke.ViewerWindow.activeInput(viewer)

viewNode = nuke.activeViewer().node()

selInput = nuke.Node.input(viewNode, actInput)

if not (os.path.exists(os.environ['TMP'] + '/tmp_images/')):

os.mkdir(os.environ['TMP'] + '/tmp_images/')

tmpDir = os.environ['TMP'] + '/tmp_images/'

tmpDir = tmpDir.replace(&quot;\\&quot;, &quot;/&quot;)

tmpName = 'shot_' + str(index)

tmpPath = tmpDir + tmpName + '.png'

write = nuke.nodes.Write(file = tmpPath1, name = 'tmpWrite', file_type='png')

write.setInput(0,selInput)

curFrame = int(nuke.knob(&quot;frame&quot;))

nuke.execute(write1.name(), curFrame, curFrame)

nuke.delete(write)

return tmpPath

def Get_Username():

return getpass.getuser()

def MakeSnapshot():

for a in nuke.allNodes():

if a.name() == 'tmp_read':

nuke.delete(a)

shotIndex = 0

fileName = renderCurrentFrame(shotIndex)

shotIndex += 1

rNode = nuke.nodes.Read(file=fileName, name = 'tmp_read')

vNode = nuke.activeViewer().node()

vNode.setInput(1, rNode)</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.listener.com.ba/thepage/2012/02/22/97/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New progress with GUI picker</title>
		<link>http://www.listener.com.ba/thepage/2011/04/30/new-progress-with-gui-picker/</link>
		<comments>http://www.listener.com.ba/thepage/2011/04/30/new-progress-with-gui-picker/#comments</comments>
		<pubDate>Sat, 30 Apr 2011 17:50:27 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.listener.com.ba/thepage/?p=78</guid>
		<description><![CDATA[<p><a href="http://www.listener.com.ba/thepage/wp-content/uploads/2011/04/news.png"></a>Just a news flash and update about GUI picker project I told you about in first post, the project is live and working and is basically ready for alpha version, after testing and after I make sure there are no more big bugs it will be released free of charge to the 3d community [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.listener.com.ba/thepage/wp-content/uploads/2011/04/news.png"><img class="alignleft size-full wp-image-79" title="news" src="http://www.listener.com.ba/thepage/wp-content/uploads/2011/04/news.png" alt="" width="48" height="48" /></a>Just a news flash and update about GUI picker project I told you about in first post, the project is live and working and is basically ready for alpha version, after testing and after I make sure there are no more big bugs it will be released free of charge to the 3d community you can check out video about this alpha version below.</p>
<p><object style="height: 390px; width: 550px;"><param name="movie" value="http://www.youtube.com/v/VCwS10xXeMY?version=3" /><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><embed type="application/x-shockwave-flash" width="550" height="390" src="http://www.youtube.com/v/VCwS10xXeMY?version=3" allowfullscreen="true" allowscriptaccess="always"></embed></object></p>
]]></content:encoded>
			<wfw:commentRss>http://www.listener.com.ba/thepage/2011/04/30/new-progress-with-gui-picker/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Project Article</title>
		<link>http://www.listener.com.ba/thepage/2011/04/30/code-project-article/</link>
		<comments>http://www.listener.com.ba/thepage/2011/04/30/code-project-article/#comments</comments>
		<pubDate>Sat, 30 Apr 2011 17:40:44 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[codeproject]]></category>
		<category><![CDATA[seekbar]]></category>

		<guid isPermaLink="false">http://www.listener.com.ba/thepage/?p=72</guid>
		<description><![CDATA[<p><a href="http://www.listener.com.ba/thepage/wp-content/uploads/2011/04/logo225x90.gif"></a>I published my first article at the code project, article is about seekBar its a C# control I have made as a part of much larger project. This seekBar that i have made is intended to track progress of any media while playing, make it possible to seek and jump on different times also [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.listener.com.ba/thepage/wp-content/uploads/2011/04/logo225x90.gif"><img class="alignleft size-full wp-image-73" title="logo225x90" src="http://www.listener.com.ba/thepage/wp-content/uploads/2011/04/logo225x90.gif" alt="" width="225" height="90" /></a>I published my first article at the code project, article is about seekBar its a C# control I have made as a part of much larger project. This seekBar that i have made is intended to track progress of any media while playing, make it possible to seek and jump on different times also it has a limiters on top so playing media can be limited to certain time. Article, source and examples are located on code project site <a href="http://www.codeproject.com/KB/progress/seekBarWithLimiters.aspx">here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.listener.com.ba/thepage/2011/04/30/code-project-article/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Copy files in C# with progress report</title>
		<link>http://www.listener.com.ba/thepage/2011/01/22/copy-files-in-c-with-progress-report/</link>
		<comments>http://www.listener.com.ba/thepage/2011/01/22/copy-files-in-c-with-progress-report/#comments</comments>
		<pubDate>Sat, 22 Jan 2011 13:39:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.listener.com.ba/thepage/?p=42</guid>
		<description><![CDATA[<p><a href="http://www.listener.com.ba/thepage/wp-content/uploads/2011/01/images.jpeg"></a>On my last project I had need for my application to copy files or folders (including sub dir structure). I right away had idea how simple that is, I&#8217;m sure you are thinking it too File.Copy() would suffice. Using that would give me simple copying routine and I could go along dir structure with [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.listener.com.ba/thepage/wp-content/uploads/2011/01/images.jpeg"><img class="alignleft size-full wp-image-43" title="images" src="http://www.listener.com.ba/thepage/wp-content/uploads/2011/01/images.jpeg" alt="" width="194" height="259" /></a>On my last project I had need for my application to copy files or folders (including sub dir structure). I right away had idea how simple that is, I&#8217;m sure you are thinking it too File.Copy() would suffice. Using that would give me simple copying routine and I could go along dir structure with recursion and just copy files and create directories, for a progress report I could be using ReportProgress() of the BackgroundWorker to say copying of file is done and then can iterate scroll bar with max set to total number of files. And this would work nice but I wondered if I could do it more elegant, what if user copies one big file the scrollbar would just sit there like stuck until that one file copying is finished, I needed a way to report progress how much byes of single file is copied&#8230;<span id="more-42"></span></p>
<p>So basically now that I knew what I need I was on a quest to search the Internet for something that would help me. After a few hours all I could find was a way how to do it using COM interop and its fine but i really wanted to do it solely in managed code i have found many ideas but nothing complete so I was then behind a drawing board trying to come up with something.</p>
<p>Basically idea that came to my mind was to split file and do copying one part at a time so then I could have copying progress reported after each part is copied and it would give me what I wanted report on how many bytes was copied out of file that is currently being copied. Here how I implemented it.</p>
<p>Because I wanted for UI to remain responsive whole copying is happening in a separate thread from the UI. Note that this is form that has two progress bars named progressBar1 and progressBar2 and three labels for file name currently copied, amount of KBs currently copied and nr of files remaining I don&#8217;t display code for adding progress bars or labels to the form because I assume you know this already or can use simple drag and drop from the Toolbox in Visual Studio.</p>
<pre class="crayon-plain-tag"><code>BackgroundWorker bw;

string source = &amp;quot;&amp;quot;;
string target = &amp;quot;&amp;quot;;
bool isfile = false;
int filecount = 0;
int currentFileNr = 1;
string newFilename = &amp;quot;&amp;quot;;
bool firstdir = true;
int maxbytes = 0;

public ShowProgress(string from, string to, bool isf)
{
     InitializeComponent();

     source = from;
     target = to;
     isfile = isf;

     bw = new BackgroundWorker();
     bw.DoWork += new DoWorkEventHandler(bw_DoWork);
     bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
     bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
     bw.WorkerReportsProgress = true;

     GetFileData();
}</code></pre>
<p>Basically here I initialise BackgroundWorker along and parse some data required by the constructor like source, target and isfile is a variable that indicates is the source file or is it a directory (this is just because of specific use of application it can be removed for your use). So after initialisation I call GetFileData() func.</p>
<pre class="crayon-plain-tag"><code>private void GetFileData()
{
     if (isfile)
     {
      FileInfo fi = new FileInfo(source);
      maxbytes = Convert.ToInt32(fi.Length);
      //
      //set progress bar length
      //
      progressBar1.Maximum = maxbytes;
      progressBar2.Maximum = 1;

      bw.RunWorkerAsync();
     }
     else
     {
      GetDirectoryInfo(source);
      //
      //set progress bar length
      //
      progressBar1.Maximum = maxbytes;
      progressBar2.Maximum = filecount;

      bw.RunWorkerAsync();
     }
}</code></pre><p><p>Ok here I collect some general information about what is to be copied, if (isfile) then i just get info about file to be copied set progressBar1 maximum size to bytesize of file and set progressBar2 maximum size to 1 because its only one file in question and run thread. If its not file in question then I call GetDirectoryInfo(source) function that collects info about source dir.</p>
<pre class="crayon-plain-tag"><code>private void GetDirectoryInfo(string source)
{
     string[] files = Directory.GetFiles(source);
     foreach (string file in files)
     {
      FileInfo fi = new FileInfo(file);
      maxbytes += Convert.ToInt32(fi.Length);
      filecount += 1;
     }
     string[] folders = Directory.GetDirectories(source);
     foreach (string folder in folders)
     {
      GetDirectoryInfo(folder);
     }
}</code></pre><p><p>
<p>GetDirectoryInfo() function is recursive function that collects info about source dir. it gets all files from dir then for each file it gets bytecount and stores it in a maxbytes variable that will be used as maximum value for progressBar1 and for each file it increments filecount variable counting how many files are in the source location, filecount variable is then passed as maximum of progressBar2, after all this is done function GetFileData sets maximum for progress bars and calls a new thread to begin executing copying routine.</p>
<pre class="crayon-plain-tag"><code>void bw_DoWork(object sender, DoWorkEventArgs e)
{
     if (isfile)
     {
          FileStream fs = new FileStream(source, FileMode.Open);
          long FileSize = fs.Length;
          FileInfo fi = new FileInfo(source);
          byte[] bBuffer = new byte[(int)FileSize];
          fs.Read(bBuffer, 0, (int)FileSize);
          fs.Close();
          UpdateLabels(fi.FullName);
          newFilename = fi.Name;

          if (File.Exists(target + &amp;quot;\\&amp;quot; + fi.Name))
          {
               Random rand = new Random();
               string[] nfn = newFilename.Split('.');
               newFilename = nfn[0] + &amp;quot;_&amp;quot; + rand.Next(1, 10000) + &amp;quot;.&amp;quot; + nfn[1];
          }
          FileStream fss = new FileStream(target + &amp;quot;\\&amp;quot; + newFilename, FileMode.CreateNew);
          BinaryWriter biwr = new BinaryWriter(fss);

          for (int i = 0; i &amp;lt; bBuffer.Length; i+=5000)
          {
              if (i + 5000 &amp;lt; bBuffer.Length)
              {
                   biwr.Write(bBuffer, i, 5000);
                   bw.ReportProgress(5000);
              }
              else
              {
                   biwr.Write(bBuffer, i, bBuffer.Length - i);
                   bw.ReportProgress(bBuffer.Length - i);
              }
          }
          biwr.Close();
          fss.Close();
     }
     else
     {
          string[] temp = source.Split('\\');
          target += &amp;quot;\\&amp;quot; + temp[temp.Count() - 1];
          DirectoryInfo s = new DirectoryInfo(source);
          DirectoryInfo t = new DirectoryInfo(target);
          CopyDirectory(s, t);
     }
 }</code></pre><p><p><p>
<p>here is where most of it happens first I check is it file. If its file I use FileStream to open it and then read a file in to  byte array then close the FileStream so basically I have the file put in to byte array then all that is left to check if a file exists already on the target location in my case for the needs of this specific application if file already exist on target location I append random number to file name but easily you can show some dialogue and ask user what to do. Then I create new file on target location and use BinaryWriter to write data from byte array to it using a for loop writing 5000 bytes at a time I just do checks if a file is smaller than that or if what&#8217;s left to be written is smaller than that and if it is the whole file will be written at once. You can of course change this 5000 bytes to whatever you feel like but keep it reasonable I tested this method of copying 5000 bytes at a time with regular file copying in windows and the times I get are equal sometimes maybe one or two seconds slower, since this application is planned to work in local area network testing was done copying file over network, if it comes slower at copying files on one computer you can probably increase copying chunks to 10000 or more and it should give you same results.</p>
<p>Now if the source in question is directory and not file the copying is done using CopyDirectory() function that is called from background workers do work method.</p>
<pre class="crayon-plain-tag"><code>public void CopyDirectory(DirectoryInfo di_source, DirectoryInfo di_target)
{
     if (Directory.Exists(di_target.FullName) == false)
     {
          Directory.CreateDirectory(di_target.FullName);
     }
     else
     {
          if (firstdir)
          {
               Random rand = new Random();
               string newdir = di_target.FullName + &amp;quot;_&amp;quot; + rand.Next(1, 10000);
               Directory.CreateDirectory(newdir);
               di_target = new DirectoryInfo(newdir);
               firstdir = false;
          }
     }
     foreach (FileInfo fi in di_source.GetFiles())
     {
          newFilename = fi.Name;
          FileStream fs = new FileStream(fi.FullName, FileMode.Open);
          long FileSize = fs.Length;
          byte[] bBuffer = new byte[(int)FileSize];
          fs.Read(bBuffer, 0, (int)FileSize);
          fs.Close();

          UpdateLabels(fi.FullName);

          if (File.Exists(di_target.ToString() + &amp;quot;\\&amp;quot; + fi.Name))
          {
               Random rand = new Random();
               newFilename = newFilename + &amp;quot;_&amp;quot; + rand.Next(1, 10000);
          }
          FileStream fss = new FileStream(di_target.ToString() + &amp;quot;\\&amp;quot; + newFilename,                FileMode.CreateNew );
          BinaryWriter biwr = new BinaryWriter(fss);

          for (int i = 0; i &amp;lt; bBuffer.Length; i += 500000)
          {
               if (i + 500000 &amp;lt; bBuffer.Length)
               {
                    biwr.Write(bBuffer, i, 500000);
                    bw.ReportProgress(500000);
               }
               else
               {
                    biwr.Write(bBuffer, i, bBuffer.Length - i);
                    bw.ReportProgress(bBuffer.Length - i);
               }
          }
          biwr.Close();
          fss.Close();
     }
     foreach (DirectoryInfo di_SourceSubDir in di_source.GetDirectories())
     {
          DirectoryInfo nextSubDir = di_target.CreateSubdirectory(di_SourceSubDir.Name);
          CopyDirectory(di_SourceSubDir, nextSubDir);
     }
}</code></pre><p><p><p><p>
<p>This is the function that copies complete directory structure from source to target it does so by using recursion. First part of function checks if a directory allreday exists if it does exist it appends a random number to directory name before creating it (Again this is needed by application I am using this copy routine in you can simply exchange it with something else like asking user what to do). It will rename only first directory and all other subdirs will remain intact so at first run it checks if dir exists in target if it does it checks if its the first directory by checking the status of firstdir variable if its true it appends random number to directory name and sets firstdir variable to false so subdirs of directory that is being copied are not renamed.</p>
<p>Then function basically does the same routine like if its case of one file, for each file in target dir it checks if file exists if it exists it appends to its name random number (this is leftover while working with previous versions of this copying routine now because it changes the name of directory if it allreday exists there is no need for this check and you can remove it if you like). Afterwards it simply repeats same routine like with single file, reads it in byte array and writes it in chunks of 5000 bytes. After it has written all the files in source dir it calls it self (recursion) for each subdir in source dir and repeats the process.</p>
<p>Each time one chunk of 5000 bytes is written bw.ReportProgress() is called so I can update progress bars.</p>
<pre class="crayon-plain-tag"><code>void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
     progressBar1.Value += e.ProgressPercentage;
     int copied = progressBar1.Value / 1024;
     int total = maxbytes / 1024;
     lbl_kbscopied.Text = copied + &amp;quot;/&amp;quot; + total;
}</code></pre><p><p><p><p><p>
<p>This updates progressBar1 value incrementing it and shows in label how many kilobytes are copied so far.</p>
<p>For updating label texts and progressBar2 that shows how many files are copied so far I use delegate.</p>
<pre class="crayon-plain-tag"><code>delegate void UpdateLabelsDelegate(string filename);

void UpdateLabels(string fname)
{
     if (!InvokeRequired)
     {
          lbl_filename.Text = &amp;quot;Copying: &amp;quot; + fname;
          lbl_filenr.Text = &amp;quot;File: &amp;quot; + currentFileNr + &amp;quot;/&amp;quot; + filecount;
          currentFileNr++;
          progressBar2.Value += 1;
     }
     else
     {
          Invoke(new UpdateLabelsDelegate(UpdateLabels), new object[] { fname });
     }
}</code></pre><p><p><p><p><p><p>
<p>So I can set labels for filename currently copied and display how many files are left to be copied.</p>
<p>That is it, I hope this helps you on your projects I know this is probably not most efficient code but its a prototype and it works ok i know this because application that this is coded for is used daily at my work its been in testing phase for two weeks now and there is no reported problems with copying be it speed wise or some other bug.</p>
<p>All comments, suggestions are more than welcome. Thank you for bearing with me through this one.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.listener.com.ba/thepage/2011/01/22/copy-files-in-c-with-progress-report/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Hello to You!</title>
		<link>http://www.listener.com.ba/thepage/2011/01/09/hello-to-you-2/</link>
		<comments>http://www.listener.com.ba/thepage/2011/01/09/hello-to-you-2/#comments</comments>
		<pubDate>Sun, 09 Jan 2011 00:10:21 +0000</pubDate>
		<dc:creator>listener</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[general]]></category>

		<guid isPermaLink="false">http://www.listener.com.ba/thepage/?p=34</guid>
		<description><![CDATA[<p>This is officially the first post on this blog. Since i do allot of different stuff this blog will probably have posts about programming, 3d, cg, cooking, photography, games and who knows what else.But not to forget my manners let me introduce my self to you,my name is Dejan and i work as a systems [...]]]></description>
			<content:encoded><![CDATA[<p>This is officially the first post on this blog. Since i do allot of different stuff this blog will probably have posts about programming, 3d, cg, cooking, photography, games and who knows what else.But not to forget my manners let me introduce my self to you,<span id="more-34"></span>my name is Dejan and i work as a systems and network administrator and pipeline developer for a production house, working on a computer-animated film called Birds Like Us.</p>
<p>Basically my job is on one side keeping everything running in IT department, render farm, file servers, domain controllers, dns, vpn&#8217;s, routers, switches, web server etc. on the other side its R&amp;D work for the film, creating applications and possibly methods and techniques together with rest of technical department that will be used in every possible aspect of cg film making.</p>
<p>My current project is GUI Picker for 3ds max created in c# and using just a couple of lines of maxscript. You can watch WIP preview.</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="603" height="464" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://www.youtube.com/v/ysqz3oR4gpw" /><embed type="application/x-shockwave-flash" width="550" height="464" src="http://www.youtube.com/v/ysqz3oR4gpw"></embed></object></p>
<p>As this is work in progress its has quite a few new features since this video is posted and its very near to be completed, the plan is to release this tool free of charge and it will probably be announced on <a href="http://www.cgsociety.org">cgsociety </a>forum as well as <a href="http://www.scriptspot.com">scriptspot</a> and of course my blog.</p>
<p>Since i do a lot of programming a number of posts on this blog will definitely be about that i use regularly c#, maxscript, python but also deal in c++ and java. In the last few days i took a book <a href="http://www.amazon.com/Professional-Android-Application-Development-Programmer/dp/0470565527/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1294531123&amp;sr=8-1">Professional android 2 Application Development</a> since i do a lot c# these days its really easy to switch to java so I&#8217;m learning to develop for android and it is fun so far, i will post my first applications here hopefully. Also very interested in game development, game logic, AI etc.</p>
<p>I own cannon EOS 550D and use it to quench my thirst for photography I will post few pictures for sure just to share my enthusiasm for that wonderful art.</p>
<p>Well that&#8217;s it so far I&#8217;ve tried to be as short as possible but still trying to avoid saying just whatsup. Hope i haven&#8217;t suffocated you much&#8230; and looking forward in seeing you again here <img src='http://www.listener.com.ba/thepage/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Take care for now&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.listener.com.ba/thepage/2011/01/09/hello-to-you-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

