Blog Archives

directory info get files show directories C# .Net

There is sometimes a misunderstanding between a “file” and a “folder” in filesystems. In C# .Net the following is often used to list all “files” in a folder.

DirectoryInfo di = new DirectoryInfo("yourpath");

foreach (FileInfo fi in di.GetFiles()) {
//do work
}

However, even though you can specify to search containing subdirectories, the above function will not inherently list folders. If you are looking for the equivalent to “dir” or “ls”, instead use “GetFileSystemInfos()”.

            DirectoryInfo di = new DirectoryInfo("yourpath");
		
//note the difference here with getfilesysteminfos
		foreach (dynamic d in di.GetFileSystemInfos()) {
}

Note the usage of dynamic in the above example compared to the first example. This avoids any potential issues with inheritance and choosing the right class for your temp iterator variable for unboxing etc.

Change ReadOnly File Attribute in C#

Keep in mind when deleting files from code the typical override allowing users to delete anything in their path, whether it is marked readonly or not, will prevent your IO process from continuing and throw a nice little generic “access denied” error.

To resolve this, simply remove the readonly attribute on the file prior to deletion.

     if (File.GetAttributes(fullfilename) == FileAttributes.ReadOnly)
                    {
                        File.SetAttributes(fullfilename, FileAttributes.Normal);
                    }

                    File.Delete(fullfilename);

Alternatively, using FileSystemInfo (unmodified courtesy of Ken White):

private static void DeleteFileSystemInfo(FileSystemInfo fsi)
{
    fsi.Attributes = FileAttributes.Normal;
    var di = fsi as DirectoryInfo;

    if (di != null)
    {
        foreach (var dirInfo in di.GetFileSystemInfos())
            DeleteFileSystemInfo(dirInfo);
    }

    fsi.Delete();
}

References
Wordpress (Imran Akram), http://imak47.wordpress.com/2009/01/15/how-to-remove-readonly-attribute-from-a-file/
StackOverflow (Ken White), http://stackoverflow.com/questions/667381/programatically-run-cmd-exe-as-adminstrator-in-vista-c

Play Sound in .Net

Snippets below have been condensed from their original sources for brevity. See references for original articles.

All examples are in C# .Net.

Winforms:

        public static enum SoundSource {
        FromFileSystem = 0,
            FromResourceStream=1
        }

        public static void PlaySound(string Filename, SoundSource Source) {
            switch (Source) {
                case SoundSource.FromFileSystem:
                    SoundPlayer objPlayer = new SoundPlayer();
                    objPlayer.SoundLocation="C:\\" + Filename;
                    objPlayer.Play();
                    break;
                case SoundSource.FromResourceStream:
                    SoundPlayer objPlayer2 = new SoundPlayer();
                    objPlayer2.Stream = GetEmbeddedResourceStream(Filename);
                    objPlayer2.Play();
                    break;
            }
        }

        private static System.IO.Stream GetEmbeddedResourceStream(string FileName) {
            Assembly objAssembly;
            System.IO.Stream soundstream;
            objAssembly = Assembly.LoadFrom();
            
            soundstream = objAssembly.GetManifestResourceStream(FileName);
            return soundstream;
        }

ASP .Net: (create an empty div in your page called “sound_element”)

        public static void PlaySound(Page PageInstance)
        {
            ClientScriptManager ClientScript = PageInstance.ClientScript;

            string soundclipscript =
                "<script type=\"text/javascript\">" +
    "$('#sound_element').html(\"<embed src='\"+ PageInstance.ResolveUrl(\"~\") + "Sounds/ambient1.mp3" +\"' hidden=true autostart=true loop=false>\");" +
"</script>";
            
            AjaxControlToolkit.ToolkitScriptManager.RegisterStartupScript(PageInstance, PageInstance.GetType(), "playsound",
                soundclipscript, false);

        }

Note there are many ways to play audio in a page, and the above snippet is not necessarily the best approach for every browser.

New HTML5 audio tag:

<audio src="horse.ogg" controls="controls">
Your browser does not support the audio element.
</audio>

References
dotnetspider, http://www.dotnetspider.com/resources/5014-Play-Audio-File-Wav.aspx
W3C Schools, http://www.w3schools.com/html5/tag_audio.asp