Skip to content

MikeBevers.be

Putting it out there…

Archive

Tag: c#

The Solution

It’s very useful for generating safe file or folder names from text that a user inputs.

public static string CleanStringForFileSystem(string dirtyFileName)
{
	// first trim the raw string
	string safe = dirtyFileName.Trim();

	// replace spaces with hyphens
	safe = safe.Replace(" ", "-").ToLower();

	// replace any 'double spaces' with singles
	if (safe.IndexOf("--") > -1)
		while (safe.IndexOf("--") > -1)
			safe = safe.Replace("--", "-");

	// trim out illegal characters
	safe = Regex.Replace(safe, "[^a-z0-9\\-]", "");

	// trim the length
	if (safe.Length > 50)
		safe = safe.Substring(0, 49);

	// clean the beginning and end of the filename
	char[] replace = { '-', '.' };
	safe = safe.TrimStart(replace);
	safe = safe.TrimEnd(replace);

	return safe;
}

Reading a file into a Byte[] in .NET 1.1

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo(filePath).Length;
byte[] buff = br.ReadBytes((int)numBytes);
br.Close();
fs.Close();

Don’t forget to put the code in a try/catch/finally block. In finally block, call the Close() methods.

continue reading…