放下对技术的执着

选择技术的标准

选择能既好又快完成需求的,不浪费时间的、不折腾的,最主要的是自己熟悉的技术;而不是选择最新最潮的技术。许多新技术就像潮流一样,一年一个新花样,无穷无尽层出不穷。人的精力是有限的,我们不能把有限的精力放到追求无限的技术潮流上。

放下对技术的执着

技术是工具,是用来解决问题的,解决问题需要好用的工具和趁手的工具。不要沉迷于那些“洋”工具上,不要做小白鼠。如果一直沉迷其中,那么很可能的结果就是一直在坑里打转,爬不出来,最终会一事无成,到头来什么都没得到。

应该怎么做?

放下执着,不要浮躁,潜心学习基础知识,比如数据结构和算法;或学习市面上使用率最高的编程语言,如 C、C++、Java、C#、PHP、Python等。但要一定要使用它们的稳定版本,因为我们是用这些知识和工具来解决问题的,当然要用稳定成熟的。

感想

由于我是一个自由开发者,有大量的时间,曾经长期把时间浪费在了搞新技术上,投入的时间成本很大,但收益很低,因为市场上可能还不接受最新的技术,学来没什么用,只能用来装装逼。但装逼能当饭吃吗?能当钱花吗?

编程对我来说只是工作和爱好,但远远不是生活的全部。闲暇时间应该陪陪家人,或出去散散步,或锻炼身体,或看看书,或出去旅旅游,世界这么大,应该出去看看。

ASP.NET WebForm 下载文件,兼容各个浏览器,下载文件名无乱码

ASP.NET WebForm 下载文件,兼容各个浏览器,下载文件名无乱码

protected void btnDownload_Click(object sender, EventArgs e)
{
    string webPath = Request.QueryString["filename"];
    string filePath = Server.MapPath(webPath);//路径
    FileInfo fileInfo = new FileInfo(filePath);
    string fileName = fileInfo.Name; //客户端保存的文件名

    if (fileInfo.Exists == true)
    {
        const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
        byte[] buffer = new byte[ChunkSize];

        Response.Clear();
        System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
        long dataLengthToRead = iStream.Length;//获取下载的文件总大小
        Response.ContentType = "application/octet-stream";

        if (Request.UserAgent.ToLower().IndexOf("msie") > -1 )
        {   
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
        }
        else if (Request.UserAgent.ToLower().IndexOf("firefox") > -1)
        {
            //为了向客户端输出空格,需要在当客户端使用 Firefox 时特殊处理     
            Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        }
        else if (Request.UserAgent.ToLower().IndexOf("edge") > -1) // edeg浏览器
        {
            Response.AddHeader("Content-Disposition", "attachment;filename=" + ToHexString(fileName));
        }
        else
        {
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
        }

        while (dataLengthToRead > 0 && Response.IsClientConnected)
        {
            int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
            Response.OutputStream.Write(buffer, 0, lengthRead);
            Response.Flush();
            dataLengthToRead = dataLengthToRead - lengthRead;
        }
        Response.Close();
    }

}

/// <summary> 
/// 为字符串中的非英文字符编码 
/// </summary> 
/// <param name="s"></param> 
/// <returns></returns> 
public string ToHexString(string s)
{
    char[] chars = s.ToCharArray();
    StringBuilder builder = new StringBuilder();
    for (int index = 0; index < chars.Length; index++)
    {
        bool needToEncode = NeedToEncode(chars[index]);
        if (needToEncode)
        {
            string encodedString = ToHexString(chars[index]);
            builder.Append(encodedString);
        }
        else
        {
            builder.Append(chars[index]);
        }
    }
    return builder.ToString();
}
/// <summary> 
///指定 一个字符是否应该被编码 
/// </summary> 
/// <param name="chr"></param> 
/// <returns></returns> 
private bool NeedToEncode(char chr)
{
    string reservedChars = "$-_.+!*'(),@=&";
    if (chr > 127)
        return true;
    if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
        return false;
    return true;
}
/// <summary> 
/// 为非英文字符串编码 
/// </summary> 
/// <param name="chr"></param> 
/// <returns></returns> 
private string ToHexString(char chr)
{
    UTF8Encoding utf8 = new UTF8Encoding();
    byte[] encodedBytes = utf8.GetBytes(chr.ToString());
    StringBuilder builder = new StringBuilder();
    for (int index = 0; index < encodedBytes.Length; index++)
    {
        builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
    }
    return builder.ToString();
}

asp.net core显示环境信息

在razor中添加如下代码,即可在页面显示服务器的环境信息。

@inject Microsoft.Extensions.PlatformAbstractions.IRuntimeEnvironment env
<html>
    <body>
        <img src="images/ASP-NET-Banners-01.png" />
        @("Hello World")
        <footer>
            <div class="container text-center">
                &copy;@DateTime.Now.Year  <a href="http://notes.wujie.me">老吴笔记</a> Powered by @($"dotnet-{env.RuntimeType.ToLower()}-{env.RuntimeVersion} on {env.OperatingSystem}")
            </div>
        </footer>
    </body>
</html>

VC获取程序所在的目录

VC获取程序所在的目录

CString  GetCurDir()
{
                 char   sDrive[_MAX_DRIVE ];
                 char   sDir[_MAX_DIR ];
                 char   sFilename[_MAX_FNAME ], Filename[_MAX_FNAME];
                 char   sExt[_MAX_EXT ];
                 GetModuleFileName(AfxGetInstanceHandle(), Filename, _MAX_PATH);
                 _tsplitpath(Filename, sDrive, sDir, sFilename, sExt);
                 CString   homeDir(CString (sDrive) + CString(sDir));
                 int   nLen = homeDir.GetLength();

                 if (homeDir.GetAt(nLen - 1)!= '\\' )
                {
                                homeDir += '\\' ;
                }

                 return homeDir;
}

VC++获取控制台命令的输出结果

VC++获取控制台命令的输出结果

#include "stdafx.h"

#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;

BOOL ExecDosCmd(string cmd, string &output)
{
    SECURITY_ATTRIBUTES sa;
    HANDLE hRead, hWrite;

    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;
    if (!CreatePipe(&hRead, &hWrite, &sa, 0))
    {
        return FALSE;
    }
    char command[1024]; // 长达1K的命令行,够用了吧
    strcpy(command, "Cmd.exe /C ");
    strcat(command, cmd.c_str());
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    si.cb = sizeof(STARTUPINFO);
    GetStartupInfo(&si);
    si.hStdError = hWrite;  // 把创建进程的标准错误输出重定向到管道输入
    si.hStdOutput = hWrite; // 把创建进程的标准输出重定向到管道输入
    si.wShowWindow = SW_HIDE;
    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    // 关键步骤,CreateProcess函数参数意义请查阅MSDN
    if (!CreateProcess(NULL, command, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi))
    {
        CloseHandle(hWrite);
        CloseHandle(hRead);
        return FALSE;
    }
    CloseHandle(hWrite);

    char buffer[4096] = {0}; // 用4K的空间来存储输出的内容,只要不是显示文件内容,一般情况下是够用了。
    DWORD bytesRead;
    while (true)
    {
        if (ReadFile(hRead, buffer, 4095, &bytesRead, NULL) == NULL)
            break;
        // buffer中就是执行的结果,可以保存到文本,也可以直接输出
        // AfxMessageBox(buffer);   //这里是弹出对话框显示
        // cout << "----:" << endl << buffer << endl;
    }
    CloseHandle(hRead);

    output = buffer;
    return TRUE;
}

int main()
{
    string output;
    ExecDosCmd("wmic diskdrive get Caption,SerialNumber", output);
    cout << output << endl;
    return 0;
}

C++获取windows系统分区大小及使用情况

C++使用Windows SDK获取系统分区大小以及使用情况,代码如下:

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"

#include <stdint.h>
#include <windows.h>
#include <iostream>
#include <string>

using namespace std;

void TestDrive()
{
    cout << "TestDrive" << endl;
    char* lpDrives = (char *)malloc(MAX_PATH * sizeof(char ));
    memset(lpDrives, 0, MAX_PATH * sizeof (char));

    DWORD dwLen = ::GetLogicalDriveStringsA(MAX_PATH, lpDrives);
    cout << "dwLen: " << dwLen << endl;

    DWORD driver_number = dwLen / 4;
    cout << "driver_number: " << driver_number << endl;

    string driver;
    LPTSTR start;
    for (DWORD nIndex = 0; nIndex < driver_number; nIndex++)
    {
        start = lpDrives + nIndex * 4;
        cout << "........................................." << endl;
        driver.append(start);
        cout << "lpDrives + nIndex * 4: " << lpDrives + nIndex * 4 << endl;
        cout << "DRIVE_REMOVABLE: " << DRIVE_REMOVABLE << endl;
        cout << "::GetDriveType(lpDrives + nIndex * 4): " << :: GetDriveType(lpDrives + nIndex * 4) << endl;
        if (::GetDriveType (start) == DRIVE_REMOVABLE)
        {
            driver.append(start);
            if (GetVolumeInformation (start, 0, 0, 0, 0, 0, 0, 0)) //判断驱动是否准备就绪
            {
                cout << "驱动准备就绪 " << endl;
            }
        }
        uint64_t lpFreeBytesAvailable = 0;
        uint64_t lpTotalNumberOfBytes = 0;
        uint64_t lpTotalNumberOfFreeBytes = 0;
        GetDiskFreeSpaceExA(lpDrives + nIndex * 4,
                            (PULARGE_INTEGER)&lpFreeBytesAvailable,
                            (PULARGE_INTEGER)&lpTotalNumberOfBytes,
                            (PULARGE_INTEGER)&lpTotalNumberOfFreeBytes);
        cout << "lpFreeBytesAvailable: " << lpFreeBytesAvailable << endl;
        cout << "lpTotalNumberOfBytes: " << lpTotalNumberOfBytes << endl;
        cout << "lpTotalNumberOfFreeBytes: " << lpTotalNumberOfFreeBytes << endl;
    }
    std::cout << "driver: " << driver << endl;
}

int main(int argc, char *argv[])
{
    TestDrive();
    return 0;
}

ubuntu安装libuv

ubuntu安装libuv

sudo apt-get install automake libtool curl
curl -sSL https://github.com/libuv/libuv/archive/v1.4.2.tar.gz | sudo tar zxfv - -C /usr/local/src
cd /usr/local/src/libuv-1.4.2sudo sh autogen.shsudo ./configure
sudo make 
sudo make installsudo rm -rf /usr/local/src/libuv-1.4.2 && cd ~/
sudo ldconfig