Retrieve Windows Experience Rating - c#

I'm looking to retrieve a machine's windows experience rating in C#. If possible I would also like to retrieve the numbers for each component (Graphics, RAM etc.)
Is this possible?

Every time the user goes through control panel to calculate the Windows Experience Rating, the system creates a new file in %Windows%\Performance\WinSAT\DataStore\
You need to find the most recent file (they are named with the most significant date first, so finding the latest file is trivial).
These files are xml files and are easy to parse with XmlReader or other xml parser.
The section you are interested in is WinSAT\WinSPR and contains all the scores in a single section. E.g.
<WinSAT>
<WinSPR>
<SystemScore>3.7</SystemScore>
<MemoryScore>5.9</MemoryScore>
<CpuScore>5.2</CpuScore>
<CPUSubAggScore>5.1</CPUSubAggScore>
<VideoEncodeScore>5.3</VideoEncodeScore>
<GraphicsScore>3.9</GraphicsScore>
<GamingScore>3.7</GamingScore>
<DiskScore>5.2</DiskScore>
</WinSPR>
...

Same with LINQ:
var dirName = Environment.ExpandEnvironmentVariables(#"%WinDir%\Performance\WinSAT\DataStore\");
var dirInfo = new DirectoryInfo(dirName);
var file = dirInfo.EnumerateFileSystemInfos("*Formal.Assessment*.xml")
.OrderByDescending(fi => fi.LastWriteTime)
.FirstOrDefault();
if (file == null)
throw new FileNotFoundException("WEI assessment xml not found");
var doc = XDocument.Load(file.FullName);
Console.WriteLine("Processor: " + doc.Descendants("CpuScore").First().Value);
Console.WriteLine("Memory (RAM): " + doc.Descendants("MemoryScore").First().Value);
Console.WriteLine("Graphics: " + doc.Descendants("GraphicsScore").First().Value);
Console.WriteLine("Gaming graphics: " + doc.Descendants("GamingScore").First().Value);
Console.WriteLine("Primary hard disk: " + doc.Descendants("DiskScore").First().Value);
Console.WriteLine("Base score: " + doc.Descendants("SystemScore").First().Value);

Here is a snippet for VB.NET. Converted to C# (using this, I haven't actually tested the code yet, though it looks to be fine).
/// <summary>
/// Gets the base score of a computer running Windows Vista or higher.
/// </summary>
/// <returns>The String Representation of Score, or False.</returns>
/// <remarks></remarks>
public string GetBaseScore()
{
// Check if the computer has a \WinSAT dir.
if (System.IO.Directory.Exists("C:\\Windows\\Performance\\WinSAT\\DataStore"))
{
// Our method to get the most recently updated score.
// Because the program makes a new XML file on every update of the score,
// we need to calculate the most recent, just incase the owner has upgraded.
System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo("C:\\Windows\\Performance\\WinSAT\\DataStore");
System.IO.FileInfo[] fileDir = null;
System.IO.FileInfo fileMostRecent = default(IO.FileInfo);
System.DateTime LastAccessTime = default(System.DateTime);
string LastAccessPath = string.Empty;
fileDir = Dir.GetFiles;
// Loop through the files in the \WinSAT dir to find the newest one.
foreach (var fileMostRecent in fileDir)
{
if (fileMostRecent.LastAccessTime >= LastAccessTime)
{
LastAccessTime = fileMostRecent.LastAccessTime;
LastAccessPath = fileMostRecent.FullName;
}
}
// Create an XmlTextReader instance.
System.Xml.XmlTextReader xmlReadScore = new System.Xml.XmlTextReader(LastAccessPath);
// Disable whitespace handling so we don't read over them
xmlReadScore.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
// We need to get to the 25th tag, "WinSPR".
for (int i = 0; i <= 26; i++)
{
xmlReadScore.Read();
}
// Create a string variable, so we can clean up without any mishaps.
string SystemScore = xmlReadScore.ReadElementString("SystemScore");
// Clean up.
xmlReadScore.Close();
return SystemScore;
}
// Unsuccessful.
return false;
}
I guess it only returns the overall rating, but hopefully it should get you started at least. It may only be a matter of changing a filename/parameter to get the individual ratings.

Related

C# FolderBrowserDialog - how to include shared folders

I create a FolderBrowserDialog as follows (only an excerpt -not complete code):
string tempSetWorkingPath = null;
try
{
FolderBrowserDialog folderDlg = new System.Windows.Forms.FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
folderDlg.Description = "Selected your working folder. This is where your PDF files will be saved.";
folderDlg.RootFolder = Environment.SpecialFolder.MyComputer;
folderDlg.SelectedPath = (Convert.ToString(WorkingPath).Trim().Length == 0) ? ((int)Environment.SpecialFolder.MyComputer).ToString() : WorkingPath;
if (folderDlg.ShowDialog() == DialogResult.OK)
{
tempSetWorkingPath = folderDlg.SelectedPath;
}
else
{
tempSetWorkingPath = "";
}
}
...
The code works well, except the only folders that are showing are the local folders. Users have DropBox and OneDrive shared folders on their systems and to select one of those directories, the user needs to cycle through the windows user directories and select the folder from there. On some systems I have seen over the last few months, I've seen the DropBox and OneDrive directories appear below the DeskTop directory ... but I have not, despite hours of searching - found a way to achive that.
How can I achieve that?
MTIA
DWE
Given I have observed a large number of queries posted here and elsewhere regarding the inclusion of the directories, including shared directories and given the response by # Mailosz, it seems that the root folder property of the folder dialog holds the key - it Gets or sets the root folder where the browsing starts from and thats what my code was missing.
The full code to the function referred to in my question appears below, in the event it assists someone else.
/// <summary>
/// presents the user with a folder dialog
/// Returns a full qualified directory chosen by the user
/// </summary>
/// <param name="WorkingPath">if a fully qualified directory name is provided, then the folder structure in the folder dialog will open to the directory selected</param>
/// <returns>Returns a full qualified directory chosen by the user or if no directory was chosen, an empty string</returns>
public string SetWorkingPath(string WorkingPath)
{
string tempSetWorkingPath = null;
try
{
FolderBrowserDialog folderDlg = new System.Windows.Forms.FolderBrowserDialog();
// check our proposed working path and if its valid
if((!string.IsNullOrEmpty(WorkingPath) && (WorkingPath != null)))
{
if (!Directory.Exists(WorkingPath))
WorkingPath = string.Empty;
}
else // if we are empty or null set us to empty
{
WorkingPath = string.Empty;
}
folderDlg.ShowNewFolderButton = true;
folderDlg.Description = "Please select your working folder. This is where your PDF files will be saved.";
folderDlg.RootFolder = Environment.SpecialFolder.Desktop;//.MyComputer;
folderDlg.SelectedPath = (Convert.ToString(WorkingPath).Trim().Length == 0) ? ((int)Environment.SpecialFolder.MyComputer).ToString() : WorkingPath;
if (folderDlg.ShowDialog() == DialogResult.OK)
{
// make sure we have a backslash on the end of our directory string
tempSetWorkingPath = PathAddBackslash(folderDlg.SelectedPath);
}
else
{
// return an empty string
tempSetWorkingPath = string.Empty;
}
}
catch (Exception ex)
{
tempSetWorkingPath = string.Empty;
throw (ex);
}
return tempSetWorkingPath;
}
public string PathAddBackslash(string path)
{
// They're always one character but EndsWith is shorter than
// array style access to last path character. Change this
// if performance are a (measured) issue.
string separator1 = Path.DirectorySeparatorChar.ToString();
string separator2 = Path.AltDirectorySeparatorChar.ToString();
// Trailing white spaces are always ignored but folders may have
// leading spaces. It's unusual but it may happen. If it's an issue
// then just replace TrimEnd() with Trim(). Tnx Paul Groke to point this out.
path = path.TrimEnd();
// Argument is always a directory name then if there is one
// of allowed separators then I have nothing to do.
if (path.EndsWith(separator1) || path.EndsWith(separator2))
return path;
// If there is the "alt" separator then I add a trailing one.
// Note that URI format (file://drive:\path\filename.ext) is
// not supported in most .NET I/O functions then we don't support it
// here too. If you have to then simply revert this check:
// if (path.Contains(separator1))
// return path + separator1;
//
// return path + separator2;
if (path.Contains(separator2))
return path + separator2;
// If there is not an "alt" separator I add a "normal" one.
// It means path may be with normal one or it has not any separator
// (for example if it's just a directory name). In this case I
// default to normal as users expect.
return path + separator1;
}

Get folder hierarchy with Google Drive API [C# / .NET]

I am looking for an elegant way to get the folder hierarchy, beginning with my root folder, using the C# Google Drive API V3.
Currently, you can get the root folder and its parents by
var getRequest = driveService.Files.Get("root");
getRequest.Fields = "parents";
var file = getRequest.Execute();
but I am looking for a way to get the children, not the parents, so I can recursively go down the file structure.
Setting getRequest.Fields = 'children' is not a valid field option.
recursively fetching children is a very time consuming way to fetch the full hierarchy. Much better is to run a query to fetch all folders in a single GET (well it might take more than one if you have more than 1,000 folders) and then traverse their parent properties to build up the hierarchy in memory. Bear in mind that (afaik) there is nothing that prevents a folder hierarchy being cyclic, thus folder1 owns folder2 owns folder3 owns folder1, so whichever strategy you follow, check that you aren't in a loop.
If you're new to GDrive, it's important to realise early on that Folders are simply labels, rather than containers. So cyclic relationships and files with multiple parents is quite normal. They were originally called Collections, but got renamed to Folders to appease those members of the community that couldn't get their head around labels.
I hope this is the answer you were looking for. getHeirarchy Recursively digs Google Drive and stores the file titles into a text file.
public System.IO.StreamWriter w = new System.IO.StreamWriter("Hierarchy.txt", false);
string intend = " ";
private void getHierarchy(Google.Apis.Drive.v2.Data.File Res, DriveService driveService)
{
if (Res.MimeType == "application/vnd.google-apps.folder")
{
w.Write(intend + Res.Title + " :" + Environment.NewLine);
intend += " ";
foreach (var res in ResFromFolder(driveService, Res.Id).ToList())
getHierarchy(res, driveService);
intend = intend.Remove(intend.Length - 5);
}
else
{
w.Write(intend + Res.Title + Environment.NewLine);
}
}
You can call the function something like:
w.Write("My Drive:" + Environment.NewLine);
foreach (var Res in ResFromFolder(driveService, "root").ToList())
getHierarchy(Res, driveService);
w.Close();
Here, root can be replaced with the ID of any Directory to get it's structure. This will generate the entire Drive's structure.
The ResFromFolder method returns a list of Google.Apis.Drive.v2.Data.File metadata contained in a directory.
public List<Google.Apis.Drive.v2.Data.File> ResFromFolder(DriveService service, string folderId)
{
var request = service.Children.List(folderId);
request.MaxResults = 1000;
List<Google.Apis.Drive.v2.Data.File> TList = new List<Google.Apis.Drive.v2.Data.File>();
do
{
var children = request.Execute();
foreach (ChildReference child in children.Items)
{
TList.Add(service.Files.Get(child.Id).Execute());
}
request.PageToken = children.NextPageToken;
} while (!String.IsNullOrEmpty(request.PageToken));
return TList;
}
This code produces output something like
However as pinoyyid mentioned, it does consume a good deal of time if Drive contains a large number of files and folders.
Get folder hierarchy with Google Drive API [C# / .NET]
Google.Apis.Drive.v3.DriveService service = GetService();
List<GoogleDriveFile> folderList = new List<GoogleDriveFile>();
Google.Apis.Drive.v3.FilesResource.ListRequest request = service.Files.List();
//https://developers.google.com/drenter code hereive/api/v3/search-shareddrives
request.Q = string.Format("mimeType='application/vnd.google-apps.folder' and '{0}' in parents", folderId)`enter code here`;
request.Fields = "files(id, name)";
Google.Apis.Drive.v3.Data.FileList result = request.Execute();
foreach (var file in result.Files)
{
GoogleDriveFile googleDriveFile = new GoogleDriveFile
{
Id = file.Id,
Name = file.Name,
Size = file.Size,
Version = file.Version,
CreatedTime = file.CreatedTime,
Parents = file.Parents
};
folderList.Add(googleDriveFile);
}
return folderList;

Code to reformat file

Need help formatting a seperated .txt file in C#. I have a text file that contains a directory listing and looks like as follows when I open up in notepad or ultra-edit. First column is date and time, next column is the size of file in bytes, third column is the username and fourth column is the name of the file. Each column is separated by one or more spaces, and the filename column at the end can contain spaces in the filename. They consist of more directories and the total amount of lines in the file is about 200,000.
Directory of V:\word
01/10/2013 12:30 PM 23,000 BUILTIN/ADMINISTRATOR FILE NAME.XLS
10/25/2013 10:39 AM 1,332,432 AMERICAS/DOEJ FILENAME2.CSV
11/31/2000 09:54 PM 21,999,999 AMERICAS/DOEF F_I_L_E_N_A_M_E_4.PDF
Directory of V:\word\administrators
01/10/2013 12:30 PM 23,000 BUILTIN/ADMINISTRATOR FILENAME.XLS
10/25/2013 10:39 AM 1,332,432 AMERICAS/DOEJ FILENAME2.CSV
11/31/2000 09:54 PM 21,999,999 AMERICAS/DOEF F_I_L_E_N_A_M_E_4.PDF
My goal is to try and add the path of the directory (ex. V:\Word or other directories) in a fixed format at the end of the filename. So Once you see the "Directory V:\word" then you know every line after and up until a new Directory, should show that path at the end of the filename. This would be considered the fifth column.
Here is some code, but I still need to help. I am able to get V:\word at the end of the file, but how do I read the new directory and append that to the end of the lines for all subsequent lines?
private void button1_Click(object sender, EventArgs e)
{
var sbText = new StringBuilder(10000);
string currLine = " Directory of V:\\word ";
try
{
using (StreamReader Reader = new StreamReader(#"C:\V.txt"))
{
while (!Reader.EndOfStream)
{
if (currLine != " Directory of V:\\word ")
{
MessageBox.Show("No Directory");
}
else
{
sbText.AppendLine(Reader.ReadLine() + "V:\\word");
}
}
// When all of the data has been loaded, write it to the text box in one fell swoop
richTextBox1.Text = sbText.ToString();
using (StreamWriter Writer = new StreamWriter(#"C:\NEWFILE.txt"))
{
Writer.WriteLine(sbText);
}
}
}
catch (Exception ex)
{
MessageBox.Show("An error has occured. " + ex.Message);
}
Here's a fairly straight-forward approach--which defines a simple class that represents your data, and parses each line into a class instance. It's efficient, and the results can easily be written to a new file, queried, or displayed:
void Main()
{
var lines = ReadFile();
lines.ToList().ForEach (Console.WriteLine);
}
IEnumerable<Line> ReadFile()
{
using (var reader = new StreamReader(File.OpenRead(#"file.txt")))
{
const string directoryPrefix = " Directory of ";
Regex splittingRegex = new Regex(#"\s+", RegexOptions.Compiled);
string directory = null;
string line;
while ((line = reader.ReadLine()) != null)
{
line = line.TrimEnd();
if (line.StartsWith(directoryPrefix))
{
directory = line.Substring(directoryPrefix.Length);
continue;
}
// The "6" parameter means the regex will split the string into 6 parts at most--leaving the last column (filename) unsplit
var lineParts = splittingRegex.Split(line, 6);
yield return new Line{ Date = lineParts[0], Time = lineParts[1], Period = lineParts[2], Bytes = lineParts[3], User = lineParts[4], Filename = Path.Combine(directory, lineParts[5]) };
}
}
}
// Define other methods and classes here
class Line
{
public string Date{get;set;}
public string Time {get;set;}
public string Period {get;set;}
public string Bytes {get;set;}
public string User {get;set;}
public string Filename {get;set;}
}
Note: This is derived from a couple helper methods for parsing simple text files. One of my earlier revisions include the helper methods, which might be of use to you (but aren't quite suited for this due to the need to remember the directory value).
You're incrementing wCurrLine but never resetting it. I think you want to reset it after each directory?
You're not incrementing totalLines, but then displaying it in label2. I think you should be incrementing it.
How do you check if the input line of text is a directory entry? If your text is consistent as presented, you could check the first letter of each row as it's read in and check if it is the letter 'D'.
You need to AppendLine not Append to put the carriage returns back in

Error: File Path is Too Long

i am trying to use the various file functions in C# like File.GetLastWriteTime, copy command on the file placed at the path greater than maximum allowed path on windows 7 i.e 260. Its giving me an error on long path name. On MSDN support i they have asked to use the \\?\ before the path. I did the same but still i got the same error, it seems it doesn't make any change. Below is my code. Please let me know if i am using it correct or i need to add any thing:
These all lib i am using as the code is having other things also:
the below is the respective code:
filesToBeCopied = Directory.GetFiles(path,"*",SearchOption.AllDirectories);
for (int j = 0; j < filesToBeCopied.Length; j++)
{
try
{
String filepath = #"\\?\" + filesToBeCopied[j];
File.GetLastWriteTime(filepath);
}
catch (Exception ex)
{
MessageBox.Show("Error Inside the single file iteration for the path:" +
filesToBeCopied[j] + " . The exception is :" + ex.Message);
}
}
where as path is the path to the folder at windows machine starting with drive letter. for ex.: d:\abc\bcd\cd\cdc\dc\..........
Here's a solution for at least the copying portion of your request (thank you pinvoke.net):
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
static extern bool CopyFile(string lpExistingFileName, string lpNewFileName, bool bFailIfExists);
And then to actually copy your file:
// Don't forget the '\\?\' for long paths
string reallyLongPath = #"\\?\d:\abc\bcd\cd\cdc\dc\..........";
string destination = #"C:\some\other\path\filename.txt";
CopyFile(reallyLongPath , destination, false);
As far as I know, you can't access a file directly if its path is too long (by directly, I mean using the methods of File, by creating a FileInfo via the constructor, or by using Directory.GetFiles(string fileName).
The only way I've found that will let you access such a file is to access a directory somewhere in the path before it gets too long, and then programatically walk down the tree until you get to your file, as seen here.
I've taken my code from there and modified it a little to return a FileInfo object for a file with a path that is "too long". Using this code, you can access the necessary properties on the returned FileInfo object (like LastWriteTime). It still has some limitations though, like the inability to use functions like CopyTo() or OpenText().
// Only call GetFileWithLongPath() if the path is too long
// ... otherwise, new FileInfo() is sufficient
private static FileInfo GetFile(string path)
{
if (path.Length >= MAX_FILE_PATH)
{
return GetFileWithLongPath(path);
}
else return new FileInfo(path);
}
static int MAX_FILE_PATH = 260;
static int MAX_DIR_PATH = 248;
private static FileInfo GetFileWithLongPath(string path)
{
string[] subpaths = path.Split('\\');
StringBuilder sbNewPath = new StringBuilder(subpaths[0]);
// Build longest sub-path that is less than MAX_PATH characters
for (int i = 1; i < subpaths.Length; i++)
{
if (sbNewPath.Length + subpaths[i].Length >= MAX_DIR_PATH)
{
subpaths = subpaths.Skip(i).ToArray();
break;
}
sbNewPath.Append("\\" + subpaths[i]);
}
DirectoryInfo dir = new DirectoryInfo(sbNewPath.ToString());
bool foundMatch = dir.Exists;
if (foundMatch)
{
// Make sure that all of the subdirectories in our path exist.
// Skip the last entry in subpaths, since it is our filename.
// If we try to specify the path in dir.GetDirectories(),
// We get a max path length error.
int i = 0;
while (i < subpaths.Length - 1 && foundMatch)
{
foundMatch = false;
foreach (DirectoryInfo subDir in dir.GetDirectories())
{
if (subDir.Name == subpaths[i])
{
// Move on to the next subDirectory
dir = subDir;
foundMatch = true;
break;
}
}
i++;
}
if (foundMatch)
{
// Now that we've gone through all of the subpaths, see if our file exists.
// Once again, If we try to specify the path in dir.GetFiles(),
// we get a max path length error.
foreach (FileInfo fi in dir.GetFiles())
{
if (fi.Name == subpaths[subpaths.Length - 1])
{
return fi;
}
}
}
}
// If we didn't find a match, return null;
return null;
}
Now that you've seen that, go rinse your eyes and shorten your paths.
try with this code
var path = Path.Combine(#"\\?\", filesToBeCopied[j]); //don't forget extension
"\?\" prefix to a path string tells the Windows APIs to disable all string parsing and to send the string that follows it straight to the file system.
Important : Not all file I/O APIs support "\?\", you should look at the reference topic for each API
http://www.codinghorror.com/blog/2006/11/filesystem-paths-how-long-is-too-long.html
I recently imported some source code for a customer that exceeded the maximum path limit of 256 characters.
The path you pasted was 285 characters long.
As you noted in your comment, MSDN's link here (http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx#maximum%5Fpath%5Flength) explains this length in greater detail:
In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string" where "" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)
With respect to the \\?\ functionality:
Many but not all file I/O APIs support "\?\"; you should look at the reference topic for each API to be sure.

How do you Load an MP3 file without actually using the Content class?

I am a beginner at Programming with C Sharp, and I am using the XNA SDK. I am trying to make a simple game to help my fellow classmates with studying for school, and I decided I would like it if there was some way to have them put music they want to listen to while playing the game inside of a file, and have the game automatically Load the music files, and play them in a playlist.
So far, I am able to get the game to detect whether the files are music, by detecting whether the file path name Contains(".mp3") , but I am trying to actually load the file name into a list of type Song, using a for Loop. The code looks like this.
(Declaration)
List<Song> songsToPlay;
string[] fileNames
(Initialize)
fileNames[] = Directory.GetFiles(".\Music")
(LoadContent)
for (int i = 0; i < fileNames.Count(); i++)
{
if (fileNames[i].Contains(".mp3")
{
songsToPlay.Add(fileNames[i]);
}
}
I have been trying to find a way to add a whole folder to the Content Directory, and have it do something more like
for (int i = 0; i < fileNames.Count(); i++)
{
songsToPlay.Add(Content.Load<Song>("fileNames[i]")
}
I have been unable to find some way to do this... Does anyone know how to make this work, or a better way to do this?
If you have your files in your project content, you should use the ContentManager class. It gives you more than just file loading. For example you can use Content.Unload to unload all your data when you're no longer using it.
There is no need to avoid that class. This page has an example showing exactly what you're trying to do:
public static Dictionary<string, T> LoadContent<T>(
this ContentManager contentManager, string contentFolder)
{
var dir = new DirectoryInfo(contentManager.RootDirectory
+ "\\" + contentFolder);
if (!dir.Exists)
throw new DirectoryNotFoundException();
var result = new Dictionary<string, T>();
foreach (FileInfo file in dir.GetFiles("*.mp3"))
{
string key = Path.GetFileNameWithoutExtension(file.Name);
result[key] = contentManager.Load<T>(
contentManager.RootDirectory + "/" + contentFolder + "/" + key);
}
return result;
}
You can use it like this:
var songs = Content.LoadContent<Song>("Songs");
Slight improvement to this code...
Once you get the above code working, I also suggest you make a slight change:
var dir = new DirectoryInfo(
System.IO.Path.Combine(contentManager.RootDirectory, contentFolder));
You shouldn't manually build paths via string concatenation when you can possibly avoid it. I don't know that you can do the same for ContentManager paths tho, so you might have to stick with string concatenation for that case.
Edit: Too many constructs you haven't used in class yet
Since you haven't used extension methods or the static keyword in your class yet, and probably haven't used dictionaries, here's a simpler way to do this:
string contentFolder = "Music";
var dir = new DirectoryInfo(Content.RootDirectory + "\\" + contentFolder);
if (!dir.Exists)
{
// Todo: Display a message to the user instead?
throw new DirectoryNotFoundException();
}
string[] files = dir.GetFiles("*.mp3");
for (int i = 0; i < files.Count(); ++i)
{
FileInfo file = files[i];
string key = System.IO.Path.GetFileNameWithoutExtension(file.Name);
var song = Content.Load<Song>(
Content.RootDirectory + "/" + contentFolder + "/" + key);
songsToPlay.Add(song);
}
Edit2: Some explanation of this second code sample
The DirectoryInfo class lets you load up a directory so you can enumerate all the files in it.
The GetFiles method on DirectoryInfo lets you enumerate files using a wildcard style pattern matching. Wildcard pattern matching for files means that when given these patterns:
*.* - you are looking for files named <anything>.<anything>
*.mp3 - you are looking for <anything>.mp3
throw means throwing an exception. This will deliberately stop executing code and display a good error message ("directory not found") and a line number. There is a lot to learn about exception handling, so I won't try to do it justice with a description here.
GetFileNameWithoutExtension should be obvious because it is well named.
Content.RootDirectory + "/" + contentFolder + "/" + key
That last little bit of code will build up a string containing the content root directory, the sub-directory of your songs, and each file name, using a name it can understand (since it doesn't know about filename extensions).
var means "whatever type I assign to it". It is a short-cut. For example, instead of typing:
List<string> someList = new List<string>();
You type:
var someList = new List<string>();
var has to know what type is on the right-hand-side of the assignment. It is useful because you can avoid repeating yourself.
Using var doesn't bestow any magical abilities to the variable though. You won't be able to assign a variable of a different type once you've declared the variable. It is just a short-cut for the exact same functionality.
Use the Song.FromUri method:
Song.FromUri("audio name", new Uri(#"C:\audio.mp3"));
The filepath can't contain spaces!
See here for a workaround: XNA 4 Song.fromUri containing Spaces

Categories

Resources