본문 바로가기
C# 언어

클립보드 내용을 파일로 만들기

by treeCoder 2021. 6. 27.

 

using System;
using System.Windows.Forms;

class program {

     [STAThread]

     private static void Main( ) {
           var txt = Clipboard.GetText( );

           Console.Write( "<head>" );

           foreach(char c in txt) {
                if( c == '\r' ) {
                    continue; // do nothing
                } else if( c == '\n' ) {
                    Console.Write("<tail>\n<head>" );
                } else {
                    Console.Write( c );
                }
           }
           Console.Write( "<tail>" );
     }
}

 

위의 내용을 컴파일하고, 실행하면 아래와 같다. (이 때 클립보드에 내용이 있어야 한다.)

 

 

아래 프로그램은 예를 들어 www.google.com이 이 클립보드에 저장되어 있을 때, 아래와 같은 batch file이 만들어 진다.

(이때 프로그램이 유저에게 저장할 파일 명을 물어 본다.)

 

 

 

 



using System;
using System.IO;
using System.Windows.Forms;

class program
{

    [STAThread]
    private static void Main()
    {
        // Prompt user for filename
        Console.Write("Enter filename (without extension): ");
        string filename = Console.ReadLine();
        
        string modifiedFilename = filename.Replace(" ", "_");

        // Get clipboard text
        var txt = Clipboard.GetText();

        // Build the batch script content
        string content = "@echo off\n" +
                         "start chrome " + txt;

        // Check if filename has extension
        if (Path.HasExtension(filename))
        {
            // Use the provided filename
            filename = filename + Path.GetExtension(filename);
        }
        else
        {
            // Add default .bat extension
            filename = filename + ".bat";
        }

        // Write content to the file
        try
        {
            File.WriteAllText(filename, content);
            Console.WriteLine("Batch script saved to: " + filename);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error saving file: " + ex.Message);
        }
    }
}

댓글