Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A bare-bones example of how to write alternate data streams with C#
using Microsoft.Win32.SafeHandles;
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace AlternateDataStreams
class Program
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern SafeFileHandle CreateFile(
string lpFileName,
EFileAccess dwDesiredAccess,
EFileShare dwShareMode,
IntPtr lpSecurityAttributes,
ECreationDisposition dwCreationDisposition,
EFileAttributes dwFlagsAndAttributes,
IntPtr hTemplateFile);
static void Main(string[] args)
string basePath = @"c:\Users\tekhe\temp\";
string baseFile = "funwithfiles.txt";
//First create a vanilla text file
File.WriteAllText(Path.Combine(basePath, baseFile), "This is the normal, unnamed data stream.");
//Write an image to the ADS
CreateFileWithAlternateDataStream(basePath, baseFile, ":TheKitten", "kitten.jpg");
//Write a PDF to the ADS
CreateFileWithAlternateDataStream(basePath, baseFile, ":PDFSample", "pentest.pdf");
static void CreateFileWithAlternateDataStream(string basePath, string baseFile, string streamName, string fileToWrite)
var sfh = CreateFile(basePath + baseFile + streamName,
EFileAccess.GenericRead | EFileAccess.GenericWrite,
if (sfh.IsInvalid)
using (FileStream fs = new FileStream(sfh, FileAccess.Write))
byte[] filebytes = File.ReadAllBytes(Path.Combine(basePath, fileToWrite));
fs.Write(filebytes, 0, filebytes.Length);
enum EFileAccess : uint
GenericRead = 0x80000000,
GenericWrite = 0x40000000,
GenericExecute = 0x20000000,
GenericAll = 0x10000000
public enum EFileShare : uint
None = 0x00000000,
Read = 0x00000001,
Write = 0x00000002,
Delete = 0x00000004
public enum ECreationDisposition : uint
New = 1,
CreateAlways = 2,
OpenExisting = 3,
OpenAlways = 4,
TruncateExisting = 5
public enum EFileAttributes : uint
Normal = 0x00000080
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.