Setting the file access rule of a file with C# .NET

When creating a new file you can set the access control rule for it in code. There are a couple of objects to build the puzzle.

The FileInfo class, which describes a file in a directory, has a SetAccessControl method which accepts a FileSecurity object. The FileSecurity object has an AddAccessRule method where you can pass in a FileSystemAccessRule object. The FileSystemAccessRule object has 4 overloads, 2 of which accept an IdentityReference abstract class. One of the implementations of IdentityReference is SecurityIdentifier. SecurityIdentifier in turn has 4 overloads where the last one is probably the most straightforward to use.

  • WellKnownSidType: an enumeration listing the commonly used security identifiers
  • A domainSid of type SecurityIdentifier: this can most often be ignored. Check out the MSDN link above to see which WellKnownSidType enumeration values require this

The following method will set the access control to “Everyone”, which is represented by WellKnownSidType.WorldSid. “Everyone” will have full control over the file indicated by FileSystemRights.FullControl and AccessControlType.Allow in the FileSystemAccessRule constructor:

Read more of this post

Monitor the file system with FileSystemWatcher in C# .NET

In this post we’ll look at how you can use the FileSystemWatcher object to monitor the Windows file system for various changes.

A FileSystemWatcher object enables you to be notified when some change occurs in the selected part of the file system. This can be any directory, such as “c:\” or any subdirectory under the C: drive. So if you’d like to make sure you’re notified if a change occurs on e.g. “c:\myfolder” – especially if it’s editable by your colleagues – then FileSystemWatcher is a good candidate.

Consider the following Console application:

Read more of this post

How to partially read a file with C# .NET

Say you have a large file with a lot of text in it and you need to find a particular bit. One way could be to read the entire text into memory and search through it. Another, more memory-friendly solution is to keep reading the file line by line until the search term has been found.

Suppose you have a text file with the following random English content:

Read more of this post

Using isolated storage for application-specific data in C# .NET

There’s a special storage location for a .NET application on Windows that is allocated to that application. It’s called isolated storage and it’s an optimal place to store files by an application that doesn’t have full access to the file system. Writing to and reading from isolated storage doesn’t require any extra security check. An application without full access to the file system will be able to use its allocated slot in isolated storage and nothing else. It’s an ideal mechanism for storing e.g. application state.

However, don’t confuse isolated storage with file security. It is still a “normal” location on disk with a file path. A typical location is under users/[username]/appdata/local. Therefore you or full-trust applications can still find and modify the files saved in isolated storage. However, limited-trust applications won’t be able to access any other part of the file system.

Read more of this post

Monitor the file system with FileSystemWatcher in C# .NET

In this post we’ll look at how you can use the FileSystemWatcher object to monitor the Windows file system for various changes.

A FileSystemWatcher object enables you to be notified when some change occurs in the selected part of the file system. This can be any directory, such as “c:\” or any subdirectory under the C: drive. So if you’d like to make sure you’re notified if a change occurs on e.g. “c:\myfolder” – especially if it’s editable by your colleagues – then FileSystemWatcher is a good candidate.

Consider the following Console application:

Read more of this post

Exploring a directory with the Java 8 Stream API

We saw an example of using the Java 8 Stream API in File I/O in this post. We saw how the Files object was enhanced with the lines() method to open a line reader stream to a text file.

There are other enhancements related to streams that make is simple to explore a directory on your hard drive. The following code example will collect all folders and files within the c:\gitrepos folder and add them to an ArrayList:

Path gitReposFolderPath = Paths.get("c:\\gitrepos");
gitReposFolderPath.toFile().getName();
try (Stream<Path> foldersWithinGitReposStream = Files.list(gitReposFolderPath))            
{
    List<String> elements = new ArrayList<>();
    foldersWithinGitReposStream.forEach(p -> elements.add(p.toFile().getName()));            
    System.out.println(elements);
}
catch (IOException ioe)
{

}

I got the following output:

[cryptographydotnet, dotnetformsbasedmvc5, entityframeworksixdemo, owinkatanademo, signalrdemo, singletondemoforcristian, text.txt, webapi2demo, windowsservicedemo]

The code returns both files and folders one level below the top directory, i.e. the “list” method does not dive into the subfolders. I put a text file into the folder – text.txt – just to test whether in fact all elements are returned.

Say you only need files – you can use the filter method:

foldersWithinGitReposStream.filter(p -> p.toFile().isFile()).forEach(p -> elements.add(p.toFile().getName())); 

This will only collect text.txt.

Let’s try something slightly more complex. We’ll organise the elements within the directory into a Map of Boolean and List of Paths. The key indicates whether the group of files are directories or not. We can use the collect method that we saw in this post:

try (Stream<Path> foldersWithinGitReposStream = Files.list(gitReposFolderPath))            
{
    Map<Boolean, List<Path>> collect = foldersWithinGitReposStream.collect(Collectors.groupingBy(p -> p.toFile().isDirectory()));
    System.out.println(collect);
}

This prints the following:

{false=[c:\gitrepos\text.txt], true=[c:\gitrepos\cryptographydotnet, c:\gitrepos\dotnetformsbasedmvc5, c:\gitrepos\entityframeworksixdemo, c:\gitrepos\owinkatanademo, c:\gitrepos\signalrdemo, c:\gitrepos\singletondemoforcristian, c:\gitrepos\webapi2demo, c:\gitrepos\windowsservicedemo]}

So we successfully grouped the paths.

As mentioned above the “list” method goes only one level deep. The “walk” method in turn digs deeper and extracts sub-directories as well:

try (Stream<Path> foldersWithinGitReposStream = Files.walk(gitReposFolderPath))
{
    List<String> elements = new ArrayList<>();
    foldersWithinGitReposStream.filter(p -> p.toFile().isFile()).forEach(p -> elements.add(p.toFile().getAbsolutePath()));
    System.out.println(elements);
}

We can also instruct the walk method to go n levels down with an extra integer argument:

try (Stream<Path> foldersWithinGitReposStream = Files.walk(gitReposFolderPath, 3))

View all posts related to Java here.

Packing and unpacking files using Tar archives in .NET

You must have come across files that were archives using the tar file format. Tar files are most often used on Unix systems like Linux but it happens that you need to deal with them in a .NET project.

You can find examples of .tar files throughout the Apache download pages, such this one. You’ll notice that .tar files are often also compressed using the GZip compression algorithm which together give the “.tar.gz” extension: they are files that were packed into a tar archive and then zipped using GZip. You can find an example of using GZip in .NET on this blog here. I have only little experience with Linux but I haven’t seen standalone “.tar” files yet, only ones that were compressed in some way. This is also the approach we’ll take in the example: pack and compress a group of files.

Read more of this post

Compressing and decompressing files with BZip2 in .NET C#

BZip2 is yet another data compression algorithm, similar to GZip and Deflate. There’s no native support for BZip2 (de)compression in .NET but there’s a NuGet package provided by icsharpcode.net.

Read more of this post

Packing and unpacking files using Tar archives in .NET

You must have come across files that were archives using the tar file format. Tar files are most often used on Unix systems like Linux but it happens that you need to deal with them in a .NET project.

You can find examples of .tar files throughout the Apache download pages, such this one. You’ll notice that .tar files are often also compressed using the GZip compression algorithm which together give the “.tar.gz” extension: they are files that were packed into a tar archive and then zipped using GZip. You can find an example of using GZip in .NET on this blog here. I have only little experience with Linux but I haven’t seen standalone “.tar” files yet, only ones that were compressed in some way. This is also the approach we’ll take in the example: pack and compress a group of files.

Read more of this post

5 ways to write to a file with C# .NET

It’s a common scenario that you need to write some content to a file. Here you see 5 ways to achieve that.

1. Using a FileStream:

private void WriteToAFileWithFileStream()
{
	using (FileStream target = File.Create(@"c:\mydirectory\target.txt"))
	{
		using (StreamWriter writer = new StreamWriter(target))
		{
			writer.WriteLine("Hello world");
		}
	}
}

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.